//---------------------------------------------------------------------
// File: BizTalkQuery.cs
// 
// Summary: This class is called by a BizTalk Query Service. It is 
//          responsible for querying the BizTalk Server Environment.
//          The configuration parameters are passed in.This is an 
//          Infrastructure Service helper and should not 
//          be used for Batch Processing.
//---------------------------------------------------------------------
// This file is part of the Microsoft ESB Guidance for BizTalk
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// This source code is intended only as a supplement to Microsoft BizTalk
// Server 2006 R2 release and/or on-line documentation. See these other
// materials for detailed information regarding Microsoft code samples.
//
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
// KIND, WHETHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR
// PURPOSE.
//---------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Security.Permissions;
using Microsoft.BizTalk.ExplorerOM;
using Microsoft.BizTalk.Operations;
using Microsoft.Practices.ESB.Exception.Management;
using Microsoft.Win32;
using SchemaType = Microsoft.BizTalk.ExplorerOM.SchemaType;

namespace Microsoft.Practices.ESB.BizTalkOperations
{
    /// <summary>
    /// One of the main classes called by the ESB BizTalkQueryService.cs class.
    /// The BizTalkQuery class exposes several static methods which query the BizTalk
    /// Management Database. The methods are executed through the BizTalkQueryService
    /// Web Service.
    /// </summary>
    public class BizTalkQuery : IDisposable
    {
        #region Declarations and Constructors, Destructor

        #region Constants

        private const string DefaultWCFAdapter = "WCF-BasicHttp";

        /// <summary>
        /// Message constants passed to GetMessage()  used to look up
        /// descriptions in resource file
        /// </summary>
        private const string HeartbeatQuery = "HeartbeatSql";

        private const string HostInformationQuery = "HostInformationSql";
        private const string MessageResourceBaseName = "Microsoft.Practices.ESB.BizTalkOperations.MessageResource";

        #endregion

        private static BizTalkServerRegistry bizTalkServer = new BizTalkServerRegistry();
        private readonly BizTalk.Operations.BizTalkOperations bizTalkOps;
        private readonly BtsCatalogExplorer btsExplorer;
        private bool disposed;

        /// <summary>
        /// BizTalk Quesry Construction which sets the default BizTalk Server Info.
        /// </summary>
        public BizTalkQuery()
        {
            try
            {
                // get the biztalk server and database and store at module level
                bizTalkServer = GetMgmtServerInfo();

                // Initialize our objects
                bizTalkOps =
                    new BizTalk.Operations.BizTalkOperations(bizTalkServer.BizTalkMgmtDb,
                                                             bizTalkServer.BizTalkMgmtDbName);
                btsExplorer = new BtsCatalogExplorer();
                btsExplorer.ConnectionString = ConnectionString(bizTalkServer);
            }
            catch (System.Exception ex)
            {
                // log and throw new error
                EventLogger.LogMessage(EventFormatter.FormatEvent(MethodInfo.GetCurrentMethod(), ex),
                                       EventLogEntryType.Error, (int)EventLogger.EventId.BizTalkQuery);

                throw new BizTalkQueryInitializeException(Exceptions.BizTalkQueryInitSQLMessage, ex);
            }
        }

        /// <summary>
        /// BizTalk Query Constructor which sets the BizTalk Server Paramenters
        /// </summary>
        /// <param name="serverName">BizTalk SQL Server Name</param>
        /// <param name="databaseName">BizTalk SQL Database Name</param>
        public BizTalkQuery(string serverName, string databaseName)
        {
            try
            {
                // Retrieve the local server and db name if the parameters are 
                // not passed
                if (String.IsNullOrEmpty(serverName) || String.IsNullOrEmpty(databaseName))
                {
                    bizTalkServer = GetMgmtServerInfo();
                }
                else
                {
                    bizTalkServer.BizTalkMgmtDb = databaseName;
                    bizTalkServer.BizTalkMgmtDb = serverName;
                }
                bizTalkOps =
                    new BizTalk.Operations.BizTalkOperations(bizTalkServer.BizTalkMgmtDb,
                                                             bizTalkServer.BizTalkMgmtDbName);
                btsExplorer = new BtsCatalogExplorer();
                btsExplorer.ConnectionString = ConnectionString(bizTalkServer);
            }
            catch (System.Exception ex)
            {
                // log and throw new error
                EventLogger.LogMessage(EventFormatter.FormatEvent(MethodInfo.GetCurrentMethod(), ex),
                                       EventLogEntryType.Error, (int)EventLogger.EventId.BizTalkQuery);

                throw new BizTalkQueryInitializeException(Exceptions.BizTalkQueryInitSQLMessage, ex);
            }
        }

        /// <summary>
        /// Disposes the BizTalkQuery object
        /// </summary>
        public void Dispose()
        {
            // dispose of the managed and unmanaged resources
            Dispose(true);

            // tell the GC that the Finalize process no longer needs
            // to be run for this object.
            GC.SuppressFinalize(this);
        }

        /// <summary>
        /// Disposes the BizTalkQuery object
        /// </summary>
        ~BizTalkQuery()
        {
            Dispose(false);
        }

        /// <summary>
        /// if BTExplorer object exists the object is disposed
        /// </summary>
        /// <param name="disposeManagedResources"></param>
        protected virtual void Dispose(bool disposeManagedResources)
        {
            // process only if mananged and unmanaged resources have
            // not been disposed of.
            if (!disposed)
            {
                if (disposeManagedResources)
                {
                    // dispose managed resources
                    if (null != btsExplorer)
                        btsExplorer.Dispose();
                }
                // dispose unmanaged resources
                disposed = true;
            }
        }

        #endregion

        #region Structures

        #region Nested type: BTApplication

        /// <summary>
        /// populated by Applications(),
        /// BTApplication represents the BizTalk Application information
        /// </summary>
        public struct BTApplication
        {
            private string _Description;
            private bool _IsDefaultApplication;
            private bool _IsSystem;
            private string _Name;
            private List<BTOrchestration> _Orchestrations;
            private List<BTReceivePort> _ReceivePorts;
            private List<BTSendPort> _SendPorts;
            private List<BTSchema> _Schemas;
            private List<BTPipeline> _Pipelines;

            public string Description
            {
                get { return _Description; }
                set { _Description = value; }
            }

            public string Name
            {
                get { return _Name; }
                set { _Name = value; }
            }

            public bool IsSystem
            {
                get { return _IsSystem; }
                set { _IsSystem = value; }
            }

            public bool IsDefaultApplication
            {
                get { return _IsDefaultApplication; }
                set { _IsDefaultApplication = value; }
            }

            public List<BTOrchestration> Orchestrations
            {
                get { return _Orchestrations; }
                set { _Orchestrations = value; }
            }

            public List<BTReceivePort> ReceivePorts
            {
                get { return _ReceivePorts; }
                set { _ReceivePorts = value; }
            }

            public List<BTSendPort> SendPorts
            {
                get { return _SendPorts; }
                set { _SendPorts = value; }
            }

            public List<BTSchema> Schemas
            {
                get { return _Schemas; }
                set { _Schemas = value; }
            }

            public List<BTPipeline> Pipelines
            {
                get { return _Pipelines; }
                set { _Pipelines = value; }
            }
        }

        #endregion

        #region Nested type: BTHost

        /// <summary>
        /// Represents the BizTalk Host Information
        /// </summary>
        public struct BTHost
        {
            private List<BTHostInstance> _HostInstances;
            private string _Name;
            private string _Type;

            public List<BTHostInstance> HostInstances
            {
                get { return _HostInstances; }
                set { _HostInstances = value; }
            }

            public string Name
            {
                get { return _Name; }
                set { _Name = value; }
            }

            public string Type
            {
                get { return _Type; }
                set { _Type = value; }
            }
        }

        #endregion

        #region Nested type: BTHostInstance

        /// <summary>
        /// Represents the BizTalk Host Instance Information
        /// </summary>
        public struct BTHostInstance
        {
            private DateTime _DateModified;
            private Guid _Guid;
            private string _HostInstanceName;
            private string _ServerName;
            private string _Status;

            public DateTime DateModified
            {
                get { return _DateModified; }
                set { _DateModified = value; }
            }

            public Guid Guid
            {
                get { return _Guid; }
                set { _Guid = value; }
            }

            public string HostInstanceName
            {
                get { return _HostInstanceName; }
                set { _HostInstanceName = value; }
            }

            public string ServerName
            {
                get { return _ServerName; }
                set { _ServerName = value; }
            }

            public string Status
            {
                get { return _Status; }
                set { _Status = value; }
            }
        }

        #endregion

        #region Nested type: BTOrchestration

        /// <summary>
        /// Represents the BizTalk Orchestration Information 
        /// </summary>
        public struct BTOrchestration
        {
            private string _Application;
            private string _AssemblyQualifiedName;
            private string _Description;
            private string _HostName;
            private string _Name;
            private string _Status;

            public string Status
            {
                get { return _Status; }
                set { _Status = value; }
            }

            public string Name
            {
                get { return _Name; }
                set { _Name = value; }
            }

            public string Application
            {
                get { return _Application; }
                set { _Application = value; }
            }

            public string HostName
            {
                get { return _HostName; }
                set { _HostName = value; }
            }

            public string Description
            {
                get { return _Description; }
                set { _Description = value; }
            }

            public string AssemblyQualifiedName
            {
                get { return _AssemblyQualifiedName; }
                set { _AssemblyQualifiedName = value; }
            }
        }

        #endregion

        #region Nested type: BTOrchestrationInstance

        /// <summary>
        /// Represents the BizTalk Orchestration Instance Information
        /// </summary>
        public struct BTOrchestrationInstance
        {
            private Guid _AncestorMsg;
            private string _Error;
            private Guid _Guid;
            private string _OrchestrationName;
            private string _Status;
            private DateTime _Time;

            public DateTime Time
            {
                get { return _Time; }
                set { _Time = value; }
            }

            public string Status
            {
                get { return _Status; }
                set { _Status = value; }
            }

            public string OrchestrationName
            {
                get { return _OrchestrationName; }
                set { _OrchestrationName = value; }
            }

            public Guid Guid
            {
                get { return _Guid; }
                set { _Guid = value; }
            }

            public string Error
            {
                get { return _Error; }
                set { _Error = value; }
            }

            public Guid AncestorMsg
            {
                get { return _AncestorMsg; }
                set { _AncestorMsg = value; }
            }
        }

        #endregion

        #region Nested type: BTPipeline

        /// <summary>
        /// populated by Pipelines(),
        /// BTPipeline represents the BizTalk Pipeline information
        /// </summary>
        public struct BTPipeline
        {
            private string _ApplicationName;
            private string _AssemblyQualifiedName;
            private string _Description;
            private string _FullName;
            private PipelineType _Type;

            public string FullName
            {
                get { return _FullName; }
                set { _FullName = value; }
            }

            public string ApplicationName
            {
                get { return _ApplicationName; }
                set { _ApplicationName = value; }
            }

            public string AssemblyQualifiedName
            {
                get { return _AssemblyQualifiedName; }
                set { _AssemblyQualifiedName = value; }
            }

            public string Description
            {
                get { return _Description; }
                set { _Description = value; }
            }

            public PipelineType Type
            {
                get { return _Type; }
                set { _Type = value; }
            }
        }

        #endregion

        #region Nested type: BTReceiveLocation

        /// <summary>
        /// Represents the BizTalk Receive Location Information
        /// </summary>
        public struct BTReceiveLocation
        {
            private string _Address;
            private string _ApplicationName;
            private string _CustomData;
            private string _Description;
            private bool _Enabled;
            private string _Name;
            private string _ReceiveHandlerName;
            private string _ReceivePipelineName;
            private string _ReceivePortName;
            private string _SendPipelineName;
            private BTReceiveTransportInfo _TransportInfo;
            private string _TransportType;
            private string _TransportTypeData;
            private bool _TwoWay;

            public string Name
            {
                get { return _Name; }
                set { _Name = value; }
            }

            public string Description
            {
                get { return _Description; }
                set { _Description = value; }
            }

            public string CustomData
            {
                get { return _CustomData; }
                set { _CustomData = value; }
            }

            public bool TwoWay
            {
                get { return _TwoWay; }
                set { _TwoWay = value; }
            }

            public string TransportType
            {
                get { return _TransportType; }
                set { _TransportType = value; }
            }

            public string TransportTypeData
            {
                get { return _TransportTypeData; }
                set { _TransportTypeData = value; }
            }

            public bool Enabled
            {
                get { return _Enabled; }
                set { _Enabled = value; }
            }

            public string ReceivePortName
            {
                get { return _ReceivePortName; }
                set { _ReceivePortName = value; }
            }

            public string ReceivePipelineName
            {
                get { return _ReceivePipelineName; }
                set { _ReceivePipelineName = value; }
            }

            public string SendPipelineName
            {
                get { return _SendPipelineName; }
                set { _SendPipelineName = value; }
            }

            public string ReceiveHandlerName
            {
                get { return _ReceiveHandlerName; }
                set { _ReceiveHandlerName = value; }
            }

            public string ApplicationName
            {
                get { return _ApplicationName; }
                set { _ApplicationName = value; }
            }

            public string Address
            {
                get { return _Address; }
                set { _Address = value; }
            }

            public BTReceiveTransportInfo TransportInfo
            {
                get { return _TransportInfo; }
                set { _TransportInfo = value; }
            }
        }

        #endregion

        #region Nested type: BTReceivePort

        /// <summary>
        /// Represents the BizTalk Receive Port Information
        /// </summary>
        public struct BTReceivePort
        {
            private string _ApplicationName;
            private int _Authentication;
            private string _CustomData;
            private string _Description;
            private List<string> _InboundTransforms;
            private string _Name;
            private List<string> _OutboundTransforms;
            private BTReceiveLocation _PrimaryReceiveLocation;
            private List<BTReceiveLocation> _ReceiveLocations;
            private bool _RouteFailed;
            private bool _TwoWay;

            public string Name
            {
                get { return _Name; }
                set { _Name = value; }
            }

            public string ApplicationName
            {
                get { return _ApplicationName; }
                set { _ApplicationName = value; }
            }

            public int Authentication
            {
                get { return _Authentication; }
                set { _Authentication = value; }
            }

            public bool TwoWay
            {
                get { return _TwoWay; }
                set { _TwoWay = value; }
            }

            public BTReceiveLocation PrimaryReceiveLocation
            {
                get { return _PrimaryReceiveLocation; }
                set { _PrimaryReceiveLocation = value; }
            }

            public List<BTReceiveLocation> ReceiveLocations
            {
                get { return _ReceiveLocations; }
                set { _ReceiveLocations = value; }
            }

            public string Description
            {
                get { return _Description; }
                set { _Description = value; }
            }

            public string CustomData
            {
                get { return _CustomData; }
                set { _CustomData = value; }
            }

            public bool RouteFailed
            {
                get { return _RouteFailed; }
                set { _RouteFailed = value; }
            }

            public List<string> InboundTransforms
            {
                get { return _InboundTransforms; }
                set { _InboundTransforms = value; }
            }

            public List<string> OutboundTransforms
            {
                get { return _OutboundTransforms; }
                set { _OutboundTransforms = value; }
            }
        }

        #endregion

        #region Nested type: BTSchema

        /// <summary>
        /// populated by Schemas(),
        /// BTSchema represents the BizTalk Schema information
        /// </summary>
        public struct BTSchema
        {
            private string _ApplicationName;
            private string _AssemblyQualifiedName;
            private string _Description;
            private string _FullName;
            private string _RootName;
            private string _TargetNameSpace;
            private SchemaType _Type;
            private string _XmlContent;

            public string FullName
            {
                get { return _FullName; }
                set { _FullName = value; }
            }

            public string ApplicationName
            {
                get { return _ApplicationName; }
                set { _ApplicationName = value; }
            }

            public string RootName
            {
                get { return _RootName; }
                set { _RootName = value; }
            }

            public string AssemblyQualifiedName
            {
                get { return _AssemblyQualifiedName; }
                set { _AssemblyQualifiedName = value; }
            }

            public string TargetNameSpace
            {
                get { return _TargetNameSpace; }
                set { _TargetNameSpace = value; }
            }

            public string Description
            {
                get { return _Description; }
                set { _Description = value; }
            }

            public SchemaType Type
            {
                get { return _Type; }
                set { _Type = value; }
            }

            public string XmlContent
            {
                get { return _XmlContent; }
                set { _XmlContent = value; }
            }
        }

        #endregion

        #region Nested type: BTSendPort

        /// <summary>
        /// Represents the BizTalk Send Port Information
        /// </summary>
        public struct BTSendPort
        {
            private string _Address;
            private string _ApplicationName;
            private int _Authentication;
            private string _Description;
            private string _Filter;
            private List<string> _InboundTransforms;
            private bool _IsDynamic;
            private string _Name;
            private bool _OrderedDelivery;
            private List<string> _OutboundTransforms;
            private string _ReceivePipelineName;
            private bool _RouteFailed;
            private string _SendHandlerName;
            private string _SendPipelineName;
            private string _Status;
            private BTSendTransportInfo _TransportInfo;
            private string _TransportType;
            private string _TransportTypeData;
            private bool _TwoWay;

            public bool OrderedDelivery
            {
                get { return _OrderedDelivery; }
                set { _OrderedDelivery = value; }
            }

            public int Authentication
            {
                get { return _Authentication; }
                set { _Authentication = value; }
            }

            public bool TwoWay
            {
                get { return _TwoWay; }
                set { _TwoWay = value; }
            }

            public string TransportType
            {
                get { return _TransportType; }
                set { _TransportType = value; }
            }

            public string TransportTypeData
            {
                get { return _TransportTypeData; }
                set { _TransportTypeData = value; }
            }

            public string Description
            {
                get { return _Description; }
                set { _Description = value; }
            }

            public string Status
            {
                get { return _Status; }
                set { _Status = value; }
            }

            public bool RouteFailed
            {
                get { return _RouteFailed; }
                set { _RouteFailed = value; }
            }

            public string ReceivePipelineName
            {
                get { return _ReceivePipelineName; }
                set { _ReceivePipelineName = value; }
            }

            public string SendPipelineName
            {
                get { return _SendPipelineName; }
                set { _SendPipelineName = value; }
            }

            public string Name
            {
                get { return _Name; }
                set { _Name = value; }
            }

            public List<string> InboundTransforms
            {
                get { return _InboundTransforms; }
                set { _InboundTransforms = value; }
            }

            public List<string> OutboundTransforms
            {
                get { return _OutboundTransforms; }
                set { _OutboundTransforms = value; }
            }

            public bool IsDynamic
            {
                get { return _IsDynamic; }
                set { _IsDynamic = value; }
            }

            public string SendHandlerName
            {
                get { return _SendHandlerName; }
                set { _SendHandlerName = value; }
            }

            public string Filter
            {
                get { return _Filter; }
                set { _Filter = value; }
            }

            public string ApplicationName
            {
                get { return _ApplicationName; }
                set { _ApplicationName = value; }
            }

            public string Address
            {
                get { return _Address; }
                set { _Address = value; }
            }

            public BTSendTransportInfo TransportInfo
            {
                get { return _TransportInfo; }
                set { _TransportInfo = value; }
            }
        }

        #endregion

        #region Nested type: BTSysStatus

        /// <summary>
        /// Represents the BizTalk System Status Information
        /// </summary>
        public struct BTSysStatus
        {
            private string _Error;
            private List<BTHost> _Hosts;
            private List<BTOrchestration> _Orchestrations;
            private List<BTReceivePort> _ReceivePorts;
            private List<BTSendPort> _SendPorts;

            public List<BTHost> Hosts
            {
                get { return _Hosts; }
                set { _Hosts = value; }
            }

            public List<BTSendPort> SendPorts
            {
                get { return _SendPorts; }
                set { _SendPorts = value; }
            }

            public List<BTReceivePort> ReceivePorts
            {
                get { return _ReceivePorts; }
                set { _ReceivePorts = value; }
            }

            public List<BTOrchestration> Orchestrations
            {
                get { return _Orchestrations; }
                set { _Orchestrations = value; }
            }

            public string Error
            {
                get { return _Error; }
                set { _Error = value; }
            }
        }

        #endregion

        #region Nested type: BTTransform

        /// <summary>
        /// populated by Transforms(),
        /// BTTransform represents the BizTalk Transform information
        /// </summary>
        public struct BTTransform
        {
            private string _ApplicationName;
            private string _AssemblyQualifiedName;
            private string _Description;
            private string _FullName;
            private string _SourceSchema;
            private string _TargetSchema;
            private string _XmlContent;

            public string ApplicationName
            {
                get { return _ApplicationName; }
                set { _ApplicationName = value; }
            }

            public string FullName
            {
                get { return _FullName; }
                set { _FullName = value; }
            }

            public string AssemblyQualifiedName
            {
                get { return _AssemblyQualifiedName; }
                set { _AssemblyQualifiedName = value; }
            }

            public string SourceSchema
            {
                get { return _SourceSchema; }
                set { _SourceSchema = value; }
            }

            public string TargetSchema
            {
                get { return _TargetSchema; }
                set { _TargetSchema = value; }
            }

            public string XmlContent
            {
                get { return _XmlContent; }
                set { _XmlContent = value; }
            }

            public string Description
            {
                get { return _Description; }
                set { _Description = value; }
            }
        }

        #endregion

        #region Nested type: BTSendTransportInfo

        /// <summary>
        /// BTSendTransportInfo represents the BizTalk Send Port Transport information
        /// </summary>
        public struct BTSendTransportInfo
        {
            #region File Send Port Transport Info

            public string Directory;
            public bool AllowCacheOnWrite;
            public bool UseTempFileOnWrite;
            public int CopyMode;
            public string FileName;

            #endregion

            #region FTP Send Port Transport Info

            public string ServerAddress;
            public int ServerPort;
            public string UserName;
            public string Password;
            public string TargetFolder;
            public string TargetFileName;
            public string RepresentationType;
            public bool AllocateStorage;
            public int ConnectionLimit;
            public bool PassiveMode;
            public string FirewallAddress;
            public string FirewallPassword;
            public int FirewallPort;
            public string FirewallType;
            public string FirewallUser;
            public string LogFile;
            public string TempFolder;

            #endregion

            #region SQL Send Port Transport Info

            public string ConnectionString;
            public string DBServer;
            public string DBName;
            public string DocumentTargetNamespace;
            public string OutputRootElementName;

            #endregion
        }

        #endregion

        #region Nested type: BTReceiveTransportInfo

        /// <summary>
        /// BTReceiveTransportInfo represents the BizTalk Receive Location Transport information
        /// </summary>
        public struct BTReceiveTransportInfo
        {
            #region File Receive Location Transport Info

            public string Folder;
            public string FileMask;
            public int PollingInterval;
            public int BatchSize;
            public int BatchSizeInBytes;
            public int FileNetFailRetryInt;
            public int FileNetFailRetryCount;
            public bool RemoveReceivedFiles;
            public int RemoveReceivedFileDelay;
            public int RemoveReceivedFileRetryCount;
            public int RemoveReceivedFileMaxInterval;

            #endregion

            #region FTP Receive Location Transport Info

            public string ServerAddress;
            public int ServerPort;
            public string UserName;
            public string Password;
            public string TargetFolder;
            public string CommandLogFilename;
            public string RepresentationType;
            public string SpoolingFolder;
            public int MaximumBatchSize;
            public int MaximumNumberOfFiles;
            public bool PassiveMode;
            public string FirewallType;
            public string FirewallAddress;
            public int FirewallPort;
            public string FirewallUser;
            public string FirewallPassword;
            public string PollingUnitOfMeasure;
            public int ErrorThreshold;
            public int MaxFileSize;

            #endregion

            #region SQL Send Port Transport Info

            public string ConnectionString;
            public string DBServer;
            public string DBName;
            public string DocumentTargetNamespace;
            public string OutputRootElementName;

            #endregion
        }

        #endregion

        #endregion

        #region Utilities

        /// <summary>
        /// returns a Transport Type by checking with 
        /// various conditions("MQS","HTTP","HTTPS"), fixes the string and returns it
        /// </summary>
        /// <param name="transportType">Transport Type</param>
        /// <returns>Transport Type</returns>
        private static string FixTransportType(string transportType)
        {
            try
            {
                // Set Mqseries
                if (transportType.StartsWith("MQS", StringComparison.CurrentCultureIgnoreCase))
                    transportType = "MQSeries";

                // If Http or Https, use the default WCF adapter as the 
                if ((String.Compare(transportType, "HTTP", true, CultureInfo.CurrentCulture) == 0) ||
                    (String.Compare(transportType, "HTTPS", true, CultureInfo.CurrentCulture) == 0))
                {
                    transportType = DefaultWCFAdapter;
                }

                return transportType;
            }
            catch (System.Exception ex)
            {
                // log and throw error
                EventLogger.Write(MethodInfo.GetCurrentMethod(), ex);
                throw;
            }
        }

        private static string GenerateSendURI(string transportType, BTSendTransportInfo transportInfo)
        {
            string URI = String.Empty;

            switch (transportType)
            {
                case "FILE":
                    while (transportInfo.Directory.EndsWith(@"\"))
                        transportInfo.Directory = transportInfo.Directory.Remove(transportInfo.Directory.Length - 1);
                    URI = String.Format(@"{0}\{1}", transportInfo.Directory, transportInfo.FileName);
                    break;
                case "FTP":
                    if (!String.IsNullOrEmpty(transportInfo.TargetFolder))
                    {
                        transportInfo.TargetFolder = transportInfo.TargetFolder.Replace(@"\", "/");
                        while (transportInfo.TargetFolder.StartsWith(@"/"))
                            transportInfo.TargetFolder = transportInfo.TargetFolder.Remove(0, 1);
                        while (transportInfo.TargetFolder.EndsWith(@"/"))
                            transportInfo.TargetFolder =
                                transportInfo.TargetFolder.Remove(transportInfo.TargetFolder.Length - 1);
                    }
                    URI =
                        String.Format("ftp://{0}:{1}/{2}/{3}", transportInfo.ServerAddress, transportInfo.ServerPort,
                                      transportInfo.TargetFolder, transportInfo.TargetFileName);
                    break;
                case "SQL":
                    URI = String.Format("SQL://{0}/{1}/", transportInfo.DBServer, transportInfo.DBName);
                    break;
                default:
                    break;
            }

            return URI;
        }

        private static string GenerateReceiveURI(string transportType, BTReceiveTransportInfo transportInfo)
        {
            string URI = String.Empty;

            switch (transportType)
            {
                case "FILE":
                    while (transportInfo.Folder.EndsWith(@"\"))
                        transportInfo.Folder = transportInfo.Folder.Remove(transportInfo.Folder.Length - 1);
                    URI = String.Format(@"{0}\{1}", transportInfo.Folder, transportInfo.FileMask);
                    break;
                case "FTP":
                    if (!String.IsNullOrEmpty(transportInfo.TargetFolder))
                    {
                        transportInfo.TargetFolder = transportInfo.TargetFolder.Replace(@"\", "/");
                        while (transportInfo.TargetFolder.StartsWith(@"/"))
                            transportInfo.TargetFolder = transportInfo.TargetFolder.Remove(0, 1);
                        while (transportInfo.TargetFolder.EndsWith(@"/"))
                            transportInfo.TargetFolder =
                                transportInfo.TargetFolder.Remove(transportInfo.TargetFolder.Length - 1);
                    }
                    URI =
                        String.Format("ftp://{0}:{1}/{2}/{3}", transportInfo.ServerAddress, transportInfo.ServerPort,
                                      transportInfo.TargetFolder, transportInfo.FileMask);
                    break;
                case "SQL":
                    URI = String.Format("SQL://{0}/{1}/", transportInfo.DBServer, transportInfo.DBName);
                    break;
                default:
                    break;
            }

            return URI;
        }

        private static string GenerateReceiveTransportTypeData(string transportType, BTReceiveTransportInfo transportInfo)
        {
            string transportTypeData = String.Empty;
            string FileTransportTypeData;

            switch (transportType)
            {
                // File Transport Type Data Samples
                // <CustomProps><RemoveReceivedFileRetryCount vt="19">5</RemoveReceivedFileRetryCount><RemoveReceivedFileMaxInterval vt="19">300000</RemoveReceivedFileMaxInterval><FileMask vt="8">GV2*BARSAN*.TXT</FileMask><BatchSizeInBytes vt="19">102400</BatchSizeInBytes><PollingInterval vt="19">60000</PollingInterval><BatchSize vt="19">20</BatchSize><FileNetFailRetryInt vt="19">5</FileNetFailRetryInt><RemoveReceivedFileDelay vt="19">10</RemoveReceivedFileDelay><RenameReceivedFiles vt="11">0</RenameReceivedFiles><FileNetFailRetryCount vt="19">5</FileNetFailRetryCount></CustomProps>
                case "FILE":
                    FileTransportTypeData = @"<CustomProps><RemoveReceivedFileRetryCount vt=""19"">{0}</RemoveReceivedFileRetryCount>" +
                                            @"<RemoveReceivedFileMaxInterval vt=""19"">{1}</RemoveReceivedFileMaxInterval><FileMask vt=""8"">{2}</FileMask>" +
                                            @"<BatchSizeInBytes vt=""19"">{3}</BatchSizeInBytes><PollingInterval vt=""19"">{4}</PollingInterval>" +
                                            @"<BatchSize vt=""19"">{5}</BatchSize><FileNetFailRetryInt vt=""19"">{6}</FileNetFailRetryInt>" +
                                            @"<RemoveReceivedFileDelay vt=""19"">{7}</RemoveReceivedFileDelay><RenameReceivedFiles vt=""11"">{8}</RenameReceivedFiles>" +
                                            @"<FileNetFailRetryCount vt=""19"">{9}</FileNetFailRetryCount></CustomProps>";
                    transportTypeData = String.Format(FileTransportTypeData, transportInfo.RemoveReceivedFileRetryCount, transportInfo.RemoveReceivedFileMaxInterval, 
                                                      transportInfo.FileMask, transportInfo.BatchSizeInBytes, transportInfo.PollingInterval, transportInfo.BatchSize, 
                                                      transportInfo.FileNetFailRetryInt, transportInfo.RemoveReceivedFileDelay, transportInfo.RemoveReceivedFileDelay, 
                                                      (transportInfo.RemoveReceivedFiles) ? 1 : 0, transportInfo.FileNetFailRetryCount);
                    break;
                // FTP Transport Type Data
                // <CustomProps><AdapterConfig vt="8">&lt;Config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt;&lt;serverAddress&gt;10.0.0.1&lt;/serverAddress&gt;&lt;serverPort&gt;21&lt;/serverPort&gt;&lt;userName&gt;admin&lt;/userName&gt;&lt;password&gt;d&lt;/password&gt;&lt;fileMask&gt;*.xml&lt;/fileMask&gt;&lt;targetFolder&gt;test&lt;/targetFolder&gt;&lt;commandLogFilename&gt;C:\tete.log&lt;/commandLogFilename&gt;&lt;representationType&gt;binary&lt;/representationType&gt;&lt;spoolingFolder&gt;C:\temp&lt;/spoolingFolder&gt;&lt;maximumBatchSize&gt;0&lt;/maximumBatchSize&gt;&lt;maximumNumberOfFiles&gt;0&lt;/maximumNumberOfFiles&gt;&lt;passiveMode&gt;False&lt;/passiveMode&gt;&lt;firewallType&gt;NoFirewall&lt;/firewallType&gt;&lt;firewallPort&gt;21&lt;/firewallPort&gt;&lt;pollingUnitOfMeasure&gt;Seconds&lt;/pollingUnitOfMeasure&gt;&lt;pollingInterval&gt;60&lt;/pollingInterval&gt;&lt;errorThreshold&gt;10&lt;/errorThreshold&gt;&lt;maxFileSize&gt;100&lt;/maxFileSize&gt;&lt;uri&gt;ftp://10.0.0.1:21/test/*.xml&lt;/uri&gt;&lt;/Config&gt;</AdapterConfig></CustomProps>
                case "FTP":
                    FileTransportTypeData = @"<CustomProps><AdapterConfig vt=""8"">&lt;Config xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema""&gt;" +
                                            "&lt;serverAddress&gt;{0}&lt;/serverAddress&gt;&lt;serverPort&gt;{1}&lt;/serverPort&gt;&lt;userName&gt;{2}&lt;/userName&gt;" +
                                            "&lt;password&gt;{3}&lt;/password&gt;&lt;fileMask&gt;{4}&lt;/fileMask&gt;&lt;targetFolder&gt;{5}&lt;/targetFolder&gt;" +
                                            "&lt;commandLogFilename&gt;{6}&lt;/commandLogFilename&gt;&lt;representationType&gt;{7}&lt;/representationType&gt;" +
                                            "&lt;spoolingFolder&gt;{8}&lt;/spoolingFolder&gt;&lt;maximumBatchSize&gt;{9}&lt;/maximumBatchSize&gt;" +
                                            "&lt;maximumNumberOfFiles&gt;{10}&lt;/maximumNumberOfFiles&gt;&lt;passiveMode&gt;{11}&lt;/passiveMode&gt;" +
                                            "&lt;firewallType&gt;{12}&lt;/firewallType&gt;&lt;firewallPort&gt;{13}&lt;/firewallPort&gt;" +
                                            "&lt;pollingUnitOfMeasure&gt;{14}&lt;/pollingUnitOfMeasure&gt;&lt;pollingInterval&gt;{15}&lt;/pollingInterval&gt;" +
                                            "&lt;errorThreshold&gt;{16}&lt;/errorThreshold&gt;&lt;maxFileSize&gt;{17}&lt;/maxFileSize&gt;&lt;uri&gt;{18}&lt;/uri&gt;" +
                                            "&lt;/Config&gt;</AdapterConfig></CustomProps>";
                    transportTypeData = String.Format(FileTransportTypeData, transportInfo.ServerAddress, transportInfo.ServerPort, transportInfo.UserName, transportInfo.Password, 
                                                      transportInfo.FileMask, transportInfo.TargetFolder, transportInfo.CommandLogFilename, transportInfo.RepresentationType, 
                                                      transportInfo.SpoolingFolder, transportInfo.MaximumBatchSize, transportInfo.MaximumNumberOfFiles, transportInfo.PassiveMode ? "True" : "False",
                                                      transportInfo.FirewallType, transportInfo.FirewallPort, transportInfo.PollingUnitOfMeasure, transportInfo.PollingInterval,
                                                      transportInfo.ErrorThreshold, transportInfo.MaxFileSize, GenerateReceiveURI(transportType, transportInfo));
                    break;
                // SQL Transport Type Data
                case "SQL":
                    break;
                default:
                    break;
            }

            return transportTypeData;
        }

        private static string GenerateSendTransportTypeData(string transportType, BTSendTransportInfo transportInfo)
        {
            string transportTypeData = String.Empty;

            switch (transportType)
            {
                // File Transport Type Data Samples
                // <CustomProps><UseTempFileOnWrite vt="11">0</UseTempFileOnWrite><CopyMode vt="19">2</CopyMode><FileName vt="8">%MessageID%.xml</FileName><AllowCacheOnWrite vt="11">-1</AllowCacheOnWrite></CustomProps>
                // <CustomProps><UseTempFileOnWrite vt="11">0</UseTempFileOnWrite><CopyMode vt="19">1</CopyMode><FileName vt="8">%MessageID%.xml</FileName><AllowCacheOnWrite vt="11">0</AllowCacheOnWrite></CustomProps>
                // <CustomProps><UseTempFileOnWrite vt="11">-1</UseTempFileOnWrite><CopyMode vt="19">1</CopyMode><FileName vt="8">%MessageID%.xml</FileName><AllowCacheOnWrite vt="11">-1</AllowCacheOnWrite></CustomProps>
                case "FILE":
                    string FileTransportTypeData =
                        @"<CustomProps><UseTempFileOnWrite vt=""11"">{0}</UseTempFileOnWrite><CopyMode vt=""19"">{1}</CopyMode><FileName vt=""8""></FileName><AllowCacheOnWrite vt=""11"">{2}</AllowCacheOnWrite></CustomProps>";
                    transportTypeData =
                        String.Format(FileTransportTypeData, (transportInfo.UseTempFileOnWrite) ? -1 : 0,
                                      transportInfo.CopyMode,
                                      (transportInfo.AllowCacheOnWrite) ? -1 : 0);
                    break;
                // FTP Transport Type Data
                // <CustomProps><AdapterConfig vt="8">&lt;Config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt;&lt;serverAddress&gt;10.0.0.1&lt;/serverAddress&gt;&lt;serverPort&gt;22&lt;/serverPort&gt;&lt;userName&gt;administrator&lt;/userName&gt;&lt;password&gt;password&lt;/password&gt;&lt;targetFolder&gt;test&lt;/targetFolder&gt;&lt;targetFileName&gt;    %MessageID%.xml&lt;/targetFileName&gt;&lt;representationType&gt;ASCII&lt;/representationType&gt;&lt;allocateStorage&gt;False&lt;/allocateStorage&gt;&lt;connectionLimit&gt;0&lt;/connectionLimit&gt;&lt;passiveMode&gt;False&lt;/passiveMode&gt;&lt;firewallType&gt;NoFirewall&lt;/firewallType&gt;&lt;firewallPort&gt;21&lt;/firewallPort&gt;&lt;uri&gt;ftp://10.0.0.1:22/test/%MessageID%.xml&lt;/uri&gt;&lt;/Config&gt;</AdapterConfig></CustomProps>
                // <CustomProps><AdapterConfig vt="8">&lt;Config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt;&lt;serverAddress&gt;10.1.1.1&lt;/serverAddress&gt;&lt;serverPort&gt;24&lt;/serverPort&gt;&lt;userName&gt;admin        &lt;/userName&gt;&lt;password&gt;pass    &lt;/password&gt;&lt;targetFolder&gt;test&lt;/targetFolder&gt;&lt;targetFileName&gt;FTP_%MessageID%.txt&lt;/targetFileName&gt;&lt;representationType&gt;ASCII&lt;/representationType&gt;&lt;allocateStorage&gt;False&lt;/allocateStorage&gt;&lt;connectionLimit&gt;0&lt;/connectionLimit&gt;&lt;passiveMode&gt;False&lt;/passiveMode&gt;&lt;firewallType&gt;NoFirewall&lt;/firewallType&gt;&lt;firewallPort&gt;21&lt;/firewallPort&gt;&lt;uri&gt;ftp://10.1.1.1:24/test/FTP_%MessageID%.txt&lt;/uri&gt;&lt;/Config&gt;</AdapterConfig></CustomProps>
                case "FTP":
                    string FTPTransportTypeData =
                        @"<CustomProps><AdapterConfig vt=""8"">&lt;Config xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema""&gt;&lt;serverAddress&gt;{0}&lt;/serverAddress&gt;&lt;serverPort&gt;{1}&lt;/serverPort&gt;&lt;userName&gt;{2}&lt;/userName&gt;&lt;password&gt;{3}&lt;/password&gt;&lt;targetFolder&gt;{4}&lt;/targetFolder&gt;&lt;targetFileName&gt;{5}&lt;/targetFileName&gt;&lt;representationType&gt;{6}&lt;/representationType&gt;&lt;allocateStorage&gt;{7}&lt;/allocateStorage&gt;&lt;connectionLimit&gt;{8}&lt;/connectionLimit&gt;&lt;passiveMode&gt;{9}&lt;/passiveMode&gt;&lt;firewallType&gt;{10}&lt;/firewallType&gt;&lt;firewallPort&gt;{11}&lt;/firewallPort&gt;&lt;uri&gt;{12}&lt;/uri&gt;&lt;/Config&gt;</AdapterConfig></CustomProps>";
                    transportTypeData =
                        String.Format(FTPTransportTypeData, transportInfo.ServerAddress, transportInfo.ServerPort,
                                      transportInfo.UserName,
                                      transportInfo.Password, transportInfo.TargetFolder, transportInfo.TargetFileName,
                                      transportInfo.RepresentationType, transportInfo.AllocateStorage,
                                      transportInfo.ConnectionLimit,
                                      transportInfo.PassiveMode, transportInfo.FirewallType, transportInfo.FirewallPort,
                                      GenerateSendURI(transportType, transportInfo));
                    break;
                // SQL Transport Type Data
                // <CustomProps><AdapterConfig vt="8">&lt;Send xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt;&lt;connectionString&gt;Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=NYBBizTalk;Data Source=(local)&lt;/connectionString&gt;&lt;outputRootElementName&gt;OASAPAkibetUpdateResp&lt;/outputRootElementName&gt;&lt;documentTargetNamespace&gt;http://TEB.NYB.OA.Schemas.OAAkibetUpdate&lt;/documentTargetNamespace&gt;&lt;uri&gt;SQL://(local)/NYBBizTalk/&lt;/uri&gt;&lt;/Send&gt;</AdapterConfig></CustomProps>
                // <CustomProps><AdapterConfig vt="8">&lt;Send xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt;&lt;connectionString&gt;Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=NYBBizTalk;Data Source=(local)&lt;/connectionString&gt;&lt;outputRootElementName&gt;OASAPAkibetSelectResp&lt;/outputRootElementName&gt;&lt;documentTargetNamespace&gt;http://TEB.NYB.OA.Schemas.OA_SAP_AkibetSelect&lt;/documentTargetNamespace&gt;&lt;uri&gt;SQL://(local)/NYBBizTalk/&lt;/uri&gt;&lt;/Send&gt;</AdapterConfig></CustomProps>
                case "SQL":
                    string SQLTransportTypeData =
                        @"<CustomProps><AdapterConfig vt=""8"">&lt;Send xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema""&gt;&lt;connectionString&gt;{0}&lt;/connectionString&gt;&lt;outputRootElementName&gt;{1}&lt;/outputRootElementName&gt;&lt;documentTargetNamespace&gt;{2}&lt;/documentTargetNamespace&gt;&lt;uri&gt;{3}&lt;/uri&gt;&lt;/Send&gt;</AdapterConfig></CustomProps>";
                    transportTypeData =
                        String.Format(SQLTransportTypeData, transportInfo.ConnectionString,
                                      transportInfo.OutputRootElementName,
                                      transportInfo.DocumentTargetNamespace, GenerateSendURI(transportType, transportInfo));
                    break;
                default:
                    break;
            }

            return transportTypeData;
        }

        /// <summary>
        /// looks up message/descriptions based on string code, in resource file
        /// </summary>
        /// <param name="messageCode">constant representing lookup value</param>
        /// <param name="arguments">optional arguments to format with the message 
        /// returned from the resource file</param>
        /// <returns>String from Resouce file that corresponds to messageCode</returns>
        private static string GetMessage(string messageCode, params Object[] arguments)
        {
            try
            {
                string message = ResourceStringLoader.GetMessage(messageCode,
                                                                 MessageResourceBaseName,
                                                                 Assembly.GetExecutingAssembly(), arguments);

                return message;
            }
            catch (System.Exception ex)
            {
                EventLogger.Write(MethodInfo.GetCurrentMethod(), ex);
                throw;
            }
        }

        /// <summary>
        /// looks up messages based on codes from lookup in resource file. 
        /// Calls ResourceStringLoader.GetMessage()
        /// </summary>
        /// <param name="messageCode">code represented by constant</param>
        /// <returns>string representing error code</returns>
        private static string GetMessage(string messageCode)
        {
            try
            {
                string message = ResourceStringLoader.GetMessage(messageCode,
                                                                 MessageResourceBaseName,
                                                                 Assembly.GetExecutingAssembly());

                return message;
            }
            catch (System.Exception ex)
            {
                EventLogger.Write(MethodInfo.GetCurrentMethod(), ex);
                throw;
            }
        }

        /// <summary>
        /// Reads the BizTalk key in the Registry to retreive the BizTalk managment
        /// datbase name and sql server name.  
        /// </summary>
        /// <returns>Structure containing db name and server</returns>
        [RegistryPermission(SecurityAction.Demand,
            Read = @"SOFTWARE\Microsoft\BizTalk Server\3.0\Administration")]
        private static BizTalkServerRegistry GetMgmtServerInfo()
        {
            // initialize variables
            BizTalkServerRegistry btsServerRegistry = new BizTalkServerRegistry();

            try
            {
                // Open the registry key
                string key = @"SOFTWARE\Microsoft\BizTalk Server\3.0\Administration";
                RegistryKey rk = Registry.LocalMachine.OpenSubKey(key);
                if (rk != null)
                {
                    btsServerRegistry.BizTalkMgmtDbName = (string)rk.GetValue("MgmtDBName");
                    btsServerRegistry.BizTalkMgmtDb = (string)rk.GetValue("MgmtDBServer");
                    // clean up
                    rk.Close();
                    rk = null;
                    // return
                    return btsServerRegistry;
                }
                else
                {
                    throw new BizTalkRegistryMissingException(Exceptions.BizTalkRegistryMissingMessage, key);
                }
            }
            catch (System.Exception ex)
            {
                EventLogger.Write(MethodInfo.GetCurrentMethod(), ex);
                throw;
            }
        }

        /// <summary>
        /// Finds the appropriate ProtocolType instance
        /// from the list or registered transports
        /// </summary>
        /// <param name="adapter">Name of the adapter</param>
        /// <returns>The ProtocolType instance</returns>
        public ProtocolType FindProtocolType(string adapter)
        {
            for (int i = 0; i < btsExplorer.ProtocolTypes.Count; i++)
            {
                if (btsExplorer.ProtocolTypes[i].Name == adapter)
                    return btsExplorer.ProtocolTypes[i];
            }
            return null;
        }

        /// <summary>
        /// Get Receive Handler.
        /// </summary>
        /// <param name="transportType">Receive Handler Transport Type</param>
        /// <returns>ReceiveHandler</returns>
        private ReceiveHandler FindReceiveHandlerByTransportType(string transportType)
        {
            if (String.IsNullOrEmpty(transportType))
                throw new ArgumentNullException("transportType");

            foreach (ReceiveHandler handler in btsExplorer.ReceiveHandlers)
            {
                if (handler.TransportType.Name == transportType)
                    return handler;
            }

            return null;
        }

        /// <summary>
        /// Private structure returned by BizTalkServerRegistry() returning
        /// the db name and server for BizTalk management db
        /// </summary>
        private struct BizTalkServerRegistry
        {
            private String _BizTalkMgmtDb;
            private String _BizTalkMgmtDbName;

            public string BizTalkMgmtDbName
            {
                get { return _BizTalkMgmtDbName; }
                set { _BizTalkMgmtDbName = value; }
            }

            public string BizTalkMgmtDb
            {
                get { return _BizTalkMgmtDb; }
                set { _BizTalkMgmtDb = value; }
            }
        }

        #endregion

        #region Database Connection

        /// <summary>
        /// Called by all methods requiring direct data access.
        /// This constructs a connection string
        /// for the BizTalk management database queries, from the information
        /// stored in the BizTalk registry key.
        /// </summary>
        /// <param name="btsServerRegistry">structure containing biztalk management db name and server</param>
        /// <returns>full connection string using integrated security</returns>
        private static string ConnectionString(BizTalkServerRegistry btsServerRegistry)
        {
            try
            {
                // build the connection string
                string connStr = "Data Source=" + btsServerRegistry.BizTalkMgmtDb + ";Initial Catalog=" +
                                 btsServerRegistry.BizTalkMgmtDbName + ";Integrated Security=SSPI;Connect Timeout=120";
                return connStr;
            }
            catch (System.Exception e)
            {
                throw e;
            }
        }

        #endregion

        #region Host Operations

        /// <summary>
        /// Gets Host Instance information. 
        /// Empty Host Name returns all BizTalk Server hosts.
        /// </summary>
        /// <param name="name">Biztalk Server Host Name: BizTalkServerApplication</param>
        /// <returns>List<BTQuery.BTHost></returns>
        public List<BTHost> Hosts(string name)
        {
            //empty string so loop through all hosts
            List<BTHost> retval = new List<BTHost>();
            name = name.Trim();

            try
            {
                BTHost tempHost;

                if (String.IsNullOrEmpty(name))
                {
                    foreach (Host host in btsExplorer.Hosts)
                    {
                        tempHost = HostHelper(host.Name);
                        retval.Add(tempHost);
                    }
                }
                else
                {
                    tempHost = HostHelper(name);
                    retval.Add(tempHost);
                }

                return retval;
            }
            catch (BizTalkQueryUnexpectedException bizTalkEx)
            {
                // log and throw new error
                EventLogger.LogMessage(EventFormatter.FormatEvent(MethodInfo.GetCurrentMethod(), bizTalkEx),
                                       EventLogEntryType.Error, (int)EventLogger.EventId.BizTalkQuery);
                throw;
            }
            catch (System.Exception ex)
            {
                // log and throw new error
                EventLogger.LogMessage(EventFormatter.FormatEvent(MethodInfo.GetCurrentMethod(), ex),
                                       EventLogEntryType.Error, (int)EventLogger.EventId.BizTalkQuery);

                throw new BizTalkQueryUnexpectedException(Exceptions.BizTalkQueryGetHostsMessage, ex, name);
            }
            finally
            {
                if (null != retval)
                    retval = null;
            }
        }

        /// <summary>
        /// Return A BTHost by the passed in Host Name. 
        /// Queries the BizTalk Management Database and builds the BTHost and returns it
        /// </summary>
        /// <param name="hostName">Host Name</param>
        /// <returns> BT Host</returns>
        [SqlClientPermission(SecurityAction.Demand, AllowBlankPassword = true, KeyRestrictions = "",
            KeyRestrictionBehavior = KeyRestrictionBehavior.AllowOnly)]
        private static BTHost HostHelper(string hostName)
        {
            BTHost retval = new BTHost();
            SqlCommand command = null;

            try
            {
                // Construct sql for retreiving all host information for a specific host
                string sqlCmd = GetMessage(HostInformationQuery, hostName);

                using (SqlConnection bizTalkConnection = new SqlConnection(ConnectionString(bizTalkServer)))
                {
                    bizTalkConnection.Open();
                    command = new SqlCommand(sqlCmd, bizTalkConnection);
                    SqlDataReader dataReader = command.ExecuteReader();

                    if (dataReader.HasRows)
                    {
                        //go through data set rows and fill the structure
                        retval.Name = hostName;
                        retval.HostInstances = new List<BTHostInstance>();
                        BTHostInstance tempInst;
                        while (dataReader.Read())
                        {
                            //init the BTHost struct
                            tempInst = new BTHostInstance();
                            tempInst.HostInstanceName = dataReader.GetString(0);
                            tempInst.DateModified = dataReader.GetDateTime(1);
                            tempInst.Guid = dataReader.GetGuid(2);
                            tempInst.ServerName = dataReader.GetString(4);

                            retval.HostInstances.Add(tempInst);
                        }
                        dataReader.Close();

                        for (int i = 0; i < retval.HostInstances.Count; i++)
                        {
                            tempInst = retval.HostInstances[i];
                            tempInst.Status = HostStatus(IsHostInstanceStarted(hostName, retval.HostInstances[i].Guid));
                            retval.HostInstances[i] = tempInst;
                        }
                    }
                    bizTalkConnection.Close();
                }
                return retval;
            }
            catch (System.Exception ex)
            {
                // log and throw new error
                EventLogger.Write(MethodInfo.GetCurrentMethod(), ex);
                throw;
            }
            finally
            {
                if (null != command)
                    command.Dispose();
            }
        }

        /// <summary>
        /// returns a string "Started" or "Stopped" by the passed in boolean Value
        /// </summary>
        /// <param name="enabled">Boolean (True/False)</param>
        /// <returns>Started or Stopped</returns>
        private static string HostStatus(bool enabled)
        {
            return enabled ? "Started" : "Stopped";
        }

        /// <summary>
        /// Returns a Boolean value that shows the status of the Host Instance. 
        /// Queries the BizTalk Management Database with the Host Instance Guid.
        /// If Host Name contains Isolated returns "true"
        /// </summary>
        /// <param name="hostName">Host Name</param>
        /// <param name="hostInstanceGuid">Host Instance GUID</param>
        /// <returns>returns Host Instance Status(True/False)</returns>
        [SqlClientPermissionAttribute(SecurityAction.Demand, AllowBlankPassword = true, KeyRestrictions = "",
            KeyRestrictionBehavior = KeyRestrictionBehavior.AllowOnly)]
        private static bool IsHostInstanceStarted(string hostName, Guid hostInstanceGuid)
        {
            bool retval = false;
            SqlCommand command = null;

            try
            {
                //Construct the dynamic sql to query for heart beat from msgbox
                string sqlCmd2 = GetMessage(HeartbeatQuery, hostInstanceGuid);

                //isolated hosts dont show up in heartbeat so return true - check type not name
                if (hostName.Contains("Isolated"))
                    return true;

                using (SqlConnection bizTalkConnection = new SqlConnection(ConnectionString(bizTalkServer)))
                {
                    bizTalkConnection.Open();
                    command = new SqlCommand(sqlCmd2, bizTalkConnection);
                    SqlDataReader dataReader = command.ExecuteReader();
                    if (dataReader.HasRows)
                    {
                        retval = true;
                    }
                    dataReader.Close();
                    bizTalkConnection.Close();
                }
                return retval;
            }
            catch (System.Exception ex)
            {
                // log and throw  error
                EventLogger.Write(MethodInfo.GetCurrentMethod(), ex);
                throw;
            }
            finally
            {
                if (null != command)
                    command.Dispose();
            }
        }

        #endregion

        #region Application Operations

        /// <summary>
        /// 
        /// </summary>
        /// <param name="application"></param>
        public void CreateApplication(BTApplication application)
        {
            if (String.IsNullOrEmpty(application.Name))
                throw new ArgumentNullException("application");

            try
            {
                Application app = btsExplorer.Applications[application.Name];
                if (null != app)
                    throw new BizTalkQueryUnexpectedException(Exceptions.BizTalkQueryApplicationExistsMessage,
                                                              application.Name);

                app = btsExplorer.AddNewApplication();
                app.Name = application.Name;
                app.Description = application.Description;

                btsExplorer.SaveChanges();
            }
            catch (System.Exception ex)
            {
                btsExplorer.DiscardChanges();

                // log and throw new error
                EventLogger.LogMessage(EventFormatter.FormatEvent(MethodInfo.GetCurrentMethod(), ex),
                                       EventLogEntryType.Error, (int)EventLogger.EventId.BizTalkQuery);

                throw new BizTalkQueryUnexpectedException(Exceptions.BizTalkQueryCreateApplicationMessage, ex);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="application"></param>
        public void UpdateApplication(BTApplication application)
        {
            if (String.IsNullOrEmpty(application.Name))
                throw new ArgumentNullException("application");

            try
            {
                Application app = btsExplorer.Applications[application.Name];
                if (null == app)
                    throw new BizTalkQueryUnexpectedException(Exceptions.BizTalkQueryApplicationNullMessage,
                                                              application.Name);

                app.Description = application.Description;
                btsExplorer.SaveChanges();
            }
            catch (System.Exception ex)
            {
                btsExplorer.DiscardChanges();

                // log and throw new error
                EventLogger.LogMessage(EventFormatter.FormatEvent(MethodInfo.GetCurrentMethod(), ex),
                                       EventLogEntryType.Error, (int)EventLogger.EventId.BizTalkQuery);

                throw new BizTalkQueryUnexpectedException(Exceptions.BizTalkQueryUpdateApplicationMessage, ex,
                                                          application.Name);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="applicationName"></param>
        public void DeleteApplication(string applicationName)
        {
            if (String.IsNullOrEmpty(applicationName))
                throw new ArgumentNullException("applicationName");

            try
            {
                Application app = btsExplorer.Applications[applicationName];
                if (null == app)
                    throw new BizTalkQueryUnexpectedException(Exceptions.BizTalkQueryApplicationNullMessage,
                                                              applicationName);

                btsExplorer.RemoveApplication(app);
                btsExplorer.SaveChanges();
            }
            catch (System.Exception ex)
            {
                btsExplorer.DiscardChanges();

                // log and throw new error
                EventLogger.LogMessage(EventFormatter.FormatEvent(MethodInfo.GetCurrentMethod(), ex),
                                       EventLogEntryType.Error, (int)EventLogger.EventId.BizTalkQuery);

                throw new BizTalkQueryUnexpectedException(Exceptions.BizTalkQueryDeleteApplicationMessage, ex,
                                                          applicationName);
            }
        }

        /// <summary>
        /// Returns all Application Names. 
        /// The BTQuery invokes the BizTalk Explorer, iterates through 
        /// the applications and returns the application name and description.
        /// </summary>
        /// <returns>BTApplication List</returns>
        public List<BTApplication> ApplicationList()
        {
            try
            {
                List<BTApplication> appList = new List<BTApplication>();
                foreach (Application app in btsExplorer.Applications)
                {
                    if (false == app.IsSystem)
                    {
                        BTApplication btApp = new BTApplication();
                        btApp.Name = app.Name;
                        appList.Add(btApp);
                    }
                }
                return appList;
            }
            catch (System.Exception ex)
            {
                // log and throw new error
                EventLogger.LogMessage(EventFormatter.FormatEvent(MethodInfo.GetCurrentMethod(), ex),
                                       EventLogEntryType.Error, (int)EventLogger.EventId.BizTalkQuery);

                throw new BizTalkQueryUnexpectedException(Exceptions.BizTalkQueryGetAllApplicationsMessage, ex);
            }
        }

        /// <summary>
        /// Returns all Application Names. 
        /// The BTQuery invokes the BizTalk Explorer, iterates through 
        /// the applications and returns the application name and description.
        /// </summary>
        /// <returns>BTApplication List</returns>
        public List<BTApplication> Applications()
        {
            try
            {
                List<BTApplication> appList = new List<BTApplication>();
                foreach (Application app in btsExplorer.Applications)
                {
                    if (false == app.IsSystem)
                    {
                        BTApplication btApp = new BTApplication();
                        btApp.Name = app.Name;
                        btApp.Description = app.Description;
                        btApp.IsDefaultApplication = app.IsDefaultApplication;
                        btApp.IsSystem = app.IsSystem;
                        btApp.Orchestrations = Orchestrations2(app.Orchestrations, "");
                        btApp.ReceivePorts = ReceivePorts2(app.ReceivePorts, "");
                        btApp.SendPorts = SendPorts2(app.SendPorts, "");
                        btApp.Schemas = Schemas(app.Name, "");
                        btApp.Pipelines = Pipelines(app.Name, "");
                        appList.Add(btApp);
                    }
                }
                return appList;
            }
            catch (System.Exception ex)
            {
                // log and throw new error
                EventLogger.LogMessage(EventFormatter.FormatEvent(MethodInfo.GetCurrentMethod(), ex),
                                       EventLogEntryType.Error, (int)EventLogger.EventId.BizTalkQuery);

                throw new BizTalkQueryUnexpectedException(Exceptions.BizTalkQueryGetAllApplicationsMessage, ex);
            }
        }

        /// <summary>
        /// Returns information about specific BizTalk Server Application. 
        /// The input is the Application Name. 
        /// The Services returns information about Orchestrations, 
        /// Send Ports, Receive locations and Host Information to which the application belongs. 
        /// </summary>
        /// <param name="applicationName">BizTalk Application Name</param>
        /// <returns>BTSysStatus</returns>
        public BTSysStatus ApplicationStatus(string applicationName)
        {
            if (String.IsNullOrEmpty(applicationName))
                throw new ArgumentNullException("applicationName");

            BTSysStatus btsStatus = new BTSysStatus();
            applicationName = applicationName.Trim();
            bool found = false;

            try
            {
                List<BTHost> hostList = null; // Hosts("");
                List<BTReceivePort> rcvList = null;
                List<BTSendPort> sendList = null;
                List<BTOrchestration> orchList = null;

                foreach (Application app in btsExplorer.Applications)
                {
                    if (String.Compare(app.Name, applicationName, true, CultureInfo.CurrentCulture) == 0)
                    {
                        found = true;
                        rcvList = ReceivePorts2(app.ReceivePorts, "");
                        sendList = SendPorts2(app.SendPorts, "");
                        orchList = Orchestrations2(app.Orchestrations, "");
                        break;
                    }
                }

                if (!found)
                    throw new BizTalkQueryUnexpectedException(Exceptions.BizTalkQueryApplicationStatusNotFoundMessage,
                                                              applicationName);

                btsStatus.Hosts = hostList;
                btsStatus.ReceivePorts = rcvList;
                btsStatus.SendPorts = sendList;
                btsStatus.Orchestrations = orchList;

                return btsStatus;
            }
            catch (BizTalkQueryUnexpectedException notfoundEx)
            {
                // log and throw new error
                EventLogger.LogMessage(EventFormatter.FormatEvent(MethodInfo.GetCurrentMethod(), notfoundEx),
                                       EventLogEntryType.Error, (int)EventLogger.EventId.BizTalkQuery);
                throw;
            }
            catch (System.Exception ex)
            {
                // log and throw new error
                EventLogger.LogMessage(EventFormatter.FormatEvent(MethodInfo.GetCurrentMethod(), ex),
                                       EventLogEntryType.Error, (int)EventLogger.EventId.BizTalkQuery);

                throw new BizTalkQueryUnexpectedException(Exceptions.BizTalkQueryGetApplicationStatusMessage, ex,
                                                          applicationName);
            }
        }

        #endregion

        #region Orchestration Operations

        /// <summary>
        /// Gets all the Orchestration Information. 
        /// Empty Orchestration Name returns all Orchestrations.
        /// gets all active/suspended/dehydrated orchs - orchName optional
        /// </summary>
        /// <param name=name">Orchestration Name</param>
        /// <returns>BTQuery.BTSysStatus </returns>
        public List<BTOrchestrationInstance> GetOrchestrationInstances(string name)
        {
            if (String.IsNullOrEmpty(name))
                name = String.Empty;

            name = name.Trim();
            bool byName = !String.IsNullOrEmpty(name);
            List<BTOrchestrationInstance> orchestrationList = new List<BTOrchestrationInstance>();
            BTOrchestrationInstance tempInst;
            try
            {
                foreach (Instance inst in bizTalkOps.GetServiceInstances())
                {
                    if (String.Compare(inst.Class.ToString(), "Orchestration", true, CultureInfo.CurrentCulture) == 0)
                    {
                        if (byName)
                        {
                            if (String.Compare(inst.ServiceType, name, true, CultureInfo.CurrentCulture) == 0)
                            {
                                tempInst = new BTOrchestrationInstance();
                                tempInst.OrchestrationName = inst.ServiceType;
                                tempInst.Guid = inst.ID;
                                tempInst.Status = inst.InstanceStatus.ToString();
                                tempInst.Time = inst.CreationTime;
                                tempInst.Error = inst.ErrorDescription;

                                orchestrationList.Add(tempInst);
                            }
                        }
                        else
                        {
                            tempInst = new BTOrchestrationInstance();
                            tempInst.OrchestrationName = inst.ServiceType;
                            tempInst.Guid = inst.ID;
                            tempInst.Status = inst.InstanceStatus.ToString();
                            tempInst.Time = inst.CreationTime;
                            tempInst.Error = inst.ErrorDescription;

                            orchestrationList.Add(tempInst);
                        }
                    }
                }
                return orchestrationList;
            }
            catch (System.Exception ex)
            {
                // log and throw new error
                EventLogger.LogMessage(EventFormatter.FormatEvent(MethodInfo.GetCurrentMethod(), ex),
                                       EventLogEntryType.Error, (int)EventLogger.EventId.BizTalkQuery);

                throw new BizTalkQueryUnexpectedException(Exceptions.BizTalkQueryOrchestrationInstanceMessage, ex, name);
            }
        }

        /// <summary>
        /// Gets all the Orchestration Information. 
        /// Empty Orchestration Name returns all Orchestrations.
        /// </summary>
        /// <param name="applicationName">Application Name</param>
        /// <param name="name">Orchestration Name</param>
        /// <returns>BTOrchestration Collection</returns>
        public List<BTOrchestration> Orchestrations(string applicationName, string name)
        {
            name = (String.IsNullOrEmpty(name)) ? String.Empty : name.Trim();
            try
            {
                Application app = (String.IsNullOrEmpty(applicationName))
                                      ? btsExplorer.DefaultApplication
                                      : btsExplorer.Applications[applicationName];
                if (null == app)
                    throw new BizTalkQueryUnexpectedException(Exceptions.BizTalkQueryApplicationNullMessage,
                                                              applicationName);

                return Orchestrations2(app.Orchestrations, name);
            }
            catch (BizTalkQueryUnexpectedException bizTalkEx)
            {
                // log and throw new error
                EventLogger.LogMessage(EventFormatter.FormatEvent(MethodInfo.GetCurrentMethod(), bizTalkEx),
                                       EventLogEntryType.Error, (int)EventLogger.EventId.BizTalkQuery);
                throw;
            }
            catch (System.Exception ex)
            {
                // log and throw new error
                EventLogger.LogMessage(EventFormatter.FormatEvent(MethodInfo.GetCurrentMethod(), ex),
                                       EventLogEntryType.Error, (int)EventLogger.EventId.BizTalkQuery);

                throw new BizTalkQueryUnexpectedException(Exceptions.BizTalkQueryGetOrchestrationsMessage, ex, name);
            }
        }

        /// <summary>
        /// Gets all the Orchestration Information. 
        /// iterates through the orchestration collection and if name is specified,
        /// returns orchestation collection where name matches, else returns the collection of BTOrchestation
        /// </summary>
        /// <param name="orchColl">BTOrchestration List</param>
        /// <param name="name">Orchestration name to search for</param>
        /// <returns>Collection of BTOrchestration</returns>
        private static List<BTOrchestration> Orchestrations2(BtsOrchestrationCollection orchColl, string name)
        {
            List<BTOrchestration> orchList = new List<BTOrchestration>();
            BTOrchestration tempOrch;
            bool byName = !String.IsNullOrEmpty(name);

            try
            {
                foreach (BtsOrchestration orch in orchColl)
                {
                    if (byName)
                    {
                        if (String.Compare(name, orch.FullName, true, CultureInfo.CurrentCulture) == 0)
                        {
                            tempOrch = new BTOrchestration();
                            tempOrch.Application = orch.Application.Name;
                            tempOrch.Name = orch.FullName;
                            tempOrch.AssemblyQualifiedName = orch.AssemblyQualifiedName;
                            tempOrch.Description = orch.Description;
                            tempOrch.HostName = orch.Host.Name;
                            tempOrch.Status = orch.Status.ToString();

                            orchList.Add(tempOrch);
                            break;
                        }
                    }
                    else
                    {
                        tempOrch = new BTOrchestration();
                        tempOrch.Application = orch.Application.Name;
                        tempOrch.Name = orch.FullName;
                        tempOrch.AssemblyQualifiedName = orch.AssemblyQualifiedName;
                        tempOrch.Description = orch.Description;
                        tempOrch.HostName = orch.Host.Name;
                        tempOrch.Status = orch.Status.ToString();

                        orchList.Add(tempOrch);
                    }
                }

                return orchList;
            }
            catch (System.Exception ex)
            {
                // log and throw new error
                EventLogger.Write(MethodInfo.GetCurrentMethod(), ex);
                throw;
            }
        }

        #endregion

        #region Receive Port Operations

        /// <summary>
        /// 
        /// </summary>
        /// <param name="receivePort"></param>
        public void CreateReceivePort(BTReceivePort receivePort)
        {
            if (String.IsNullOrEmpty(receivePort.ApplicationName))
                throw new ArgumentNullException("receivePort");
            if (String.IsNullOrEmpty(receivePort.Name))
                throw new ArgumentNullException("receivePort");

            try
            {
                Application app = btsExplorer.Applications[receivePort.ApplicationName];
                if (null == app)
                    throw new BizTalkQueryUnexpectedException(Exceptions.BizTalkQueryApplicationNullMessage,
                                                              receivePort.ApplicationName);

                ReceivePort rPort = app.ReceivePorts[receivePort.Name];
                if (null != rPort)
                    throw new BizTalkQueryUnexpectedException(Exceptions.BizTalkQueryReceivePortExistsMessage,
                                                              receivePort.Name);

                rPort = app.AddNewReceivePort(receivePort.TwoWay);

                rPort.Name = receivePort.Name;
                rPort.Description = receivePort.Description;
                rPort.CustomData = receivePort.CustomData;
                rPort.Authentication = (AuthenticationType)receivePort.Authentication;
                rPort.RouteFailedMessage = receivePort.RouteFailed;

                if (null != receivePort.InboundTransforms)
                {
                    foreach (string inboundTransform in receivePort.InboundTransforms)
                    {
                        for (int i = 0; i < app.Transforms.Count; i++)
                        {
                            if (app.Transforms[i].FullName == inboundTransform)
                            {
                                rPort.InboundTransforms.Add(app.Transforms[i]);
                                break;
                            }
                        }
                    }
                }

                if (receivePort.TwoWay)
                {
                    if (null != receivePort.OutboundTransforms)
                    {
                        foreach (string outboundTransform in receivePort.OutboundTransforms)
                        {
                            for (int i = 0; i < app.Transforms.Count; i++)
                            {
                                if (app.Transforms[i].FullName == outboundTransform)
                                {
                                    rPort.OutboundTransforms.Add(app.Transforms[i]);
                                    break;
                                }
                            }
                        }
                    }
                }

                btsExplorer.SaveChanges();
            }
            catch (System.Exception ex)
            {
                btsExplorer.DiscardChanges();

                // log and throw new error
                EventLogger.LogMessage(EventFormatter.FormatEvent(MethodInfo.GetCurrentMethod(), ex),
                                       EventLogEntryType.Error, (int)EventLogger.EventId.BizTalkQuery);

                throw new BizTalkQueryUnexpectedException(Exceptions.BizTalkQueryCreateReceivePortMessage, ex);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="receivePort"></param>
        public void UpdateReceivePort(BTReceivePort receivePort)
        {
            if (String.IsNullOrEmpty(receivePort.ApplicationName))
                throw new ArgumentNullException("receivePort");
            if (String.IsNullOrEmpty(receivePort.Name))
                throw new ArgumentNullException("receivePort");

            try
            {
                Application app = btsExplorer.Applications[receivePort.ApplicationName];
                if (null == app)
                    throw new BizTalkQueryUnexpectedException(Exceptions.BizTalkQueryApplicationNullMessage,
                                                              receivePort.ApplicationName);

                ReceivePort rPort = app.ReceivePorts[receivePort.Name];
                if (null == rPort)
                    throw new BizTalkQueryUnexpectedException(Exceptions.BizTalkQueryRPNullMessage, receivePort.Name);

                rPort.Description = receivePort.Description;
                rPort.CustomData = receivePort.CustomData;
                rPort.Authentication = (AuthenticationType)receivePort.Authentication;
                rPort.RouteFailedMessage = receivePort.RouteFailed;

                if (null != receivePort.InboundTransforms)
                {
                    foreach (string inboundTransform in receivePort.InboundTransforms)
                    {
                        for (int i = 0; i < app.Transforms.Count; i++)
                        {
                            if (app.Transforms[i].FullName == inboundTransform)
                            {
                                rPort.InboundTransforms.Add(app.Transforms[i]);
                                break;
                            }
                        }
                    }
                }

                if (receivePort.TwoWay)
                {
                    if (null != receivePort.OutboundTransforms)
                    {
                        foreach (string outboundTransform in receivePort.OutboundTransforms)
                        {
                            for (int i = 0; i < app.Transforms.Count; i++)
                            {
                                if (app.Transforms[i].FullName == outboundTransform)
                                {
                                    rPort.OutboundTransforms.Add(app.Transforms[i]);
                                    break;
                                }
                            }
                        }
                    }
                }

                btsExplorer.SaveChanges();
            }
            catch (System.Exception ex)
            {
                btsExplorer.DiscardChanges();

                // log and throw new error
                EventLogger.LogMessage(EventFormatter.FormatEvent(MethodInfo.GetCurrentMethod(), ex),
                                       EventLogEntryType.Error, (int)EventLogger.EventId.BizTalkQuery);

                throw new BizTalkQueryUnexpectedException(Exceptions.BizTalkQueryUpdateReceivePortMessage, ex,
                                                          receivePort.Name);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="receivePort"></param>
        public void DeleteReceivePort(BTReceivePort receivePort)
        {
            if (String.IsNullOrEmpty(receivePort.Name))
                throw new ArgumentNullException("receivePort");

            try
            {
                ReceivePort rPort = btsExplorer.ReceivePorts[receivePort.Name];
                if (null == rPort)
                    throw new BizTalkQueryUnexpectedException(Exceptions.BizTalkQueryRPNullMessage, receivePort.Name);

                btsExplorer.RemoveReceivePort(rPort);
                btsExplorer.SaveChanges();
            }
            catch (System.Exception ex)
            {
                btsExplorer.DiscardChanges();

                // log and throw new error
                EventLogger.LogMessage(EventFormatter.FormatEvent(MethodInfo.GetCurrentMethod(), ex),
                                       EventLogEntryType.Error, (int)EventLogger.EventId.BizTalkQuery);

                throw new BizTalkQueryUnexpectedException(Exceptions.BizTalkQueryDeleteReceivePortMessage, ex,
                                                          receivePort.Name);
            }
        }

        /// <summary>
        /// Gets all the Receive Port Information. 
        /// Empty Port Name returns all Receive Ports.
        /// </summary>
        /// <param name="applicationName">Application Name</param>
        /// <param name="name">Receive Port Name</param>
        /// <returns></returns>
        public List<BTReceivePort> ReceivePorts(string applicationName, string name)
        {
            name = (String.IsNullOrEmpty(name)) ? String.Empty : name.Trim();
            try
            {
                Application app = (String.IsNullOrEmpty(applicationName))
                                      ? btsExplorer.DefaultApplication
                                      : btsExplorer.Applications[applicationName];
                if (null == app)
                    throw new BizTalkQueryUnexpectedException(Exceptions.BizTalkQueryApplicationNullMessage,
                                                              applicationName);

                return ReceivePorts2(app.ReceivePorts, name);
            }
            catch (BizTalkQueryUnexpectedException bizTalkEx)
            {
                // log and throw new error
                EventLogger.LogMessage(EventFormatter.FormatEvent(MethodInfo.GetCurrentMethod(), bizTalkEx),
                                       EventLogEntryType.Error, (int)EventLogger.EventId.BizTalkQuery);
                throw;
            }
            catch (System.Exception ex)
            {
                // log and throw new error
                EventLogger.LogMessage(EventFormatter.FormatEvent(MethodInfo.GetCurrentMethod(), ex),
                                       EventLogEntryType.Error, (int)EventLogger.EventId.BizTalkQuery);

                throw new BizTalkQueryUnexpectedException(Exceptions.BizTalkQueryGetReceivePortsMessage, ex, name);
            }
        }

        /// <summary>
        /// Gets the Receive Port Information by querying the BizTalk Management Database
        /// Empty receive port Name returns all receive ports else returns specific receive port information.
        /// </summary>
        /// <param name="receivePortColl">Receive Port List</param>
        /// <param name="name">Receive port name to search for</param>
        /// <returns>BTReceivePort List</returns>
        private static List<BTReceivePort> ReceivePorts2(ReceivePortCollection receivePortColl, string name)
        {
            List<BTReceivePort> receiveList = new List<BTReceivePort>();
            BTReceivePort tempReceive;
            bool byName = !String.IsNullOrEmpty(name);

            try
            {
                foreach (ReceivePort receivePort in receivePortColl)
                {
                    if (byName)
                    {
                        if (String.Compare(name, receivePort.Name, true, CultureInfo.CurrentCulture) == 0)
                        {
                            tempReceive = new BTReceivePort();
                            tempReceive.Name = receivePort.Name;
                            tempReceive.ApplicationName = receivePort.Application.Name;
                            tempReceive.Description = receivePort.Description;
                            tempReceive.CustomData = receivePort.CustomData;
                            tempReceive.Authentication = (int)receivePort.Authentication;
                            tempReceive.TwoWay = receivePort.IsTwoWay;
                            tempReceive.RouteFailed = receivePort.RouteFailedMessage;
                            tempReceive.ReceiveLocations = ReceiveLocations2(receivePort.ReceiveLocations, "");

                            if ((null != receivePort.InboundTransforms) && (receivePort.InboundTransforms.Count > 0))
                            {
                                tempReceive.InboundTransforms = new List<string>();
                                for (int i = 0; i < receivePort.InboundTransforms.Count; i++)
                                    tempReceive.InboundTransforms.Add(
                                        ((Transform)receivePort.InboundTransforms[i]).FullName);
                            }

                            if (receivePort.IsTwoWay)
                            {
                                if ((null != receivePort.OutboundTransforms) &&
                                    (receivePort.OutboundTransforms.Count > 0))
                                {
                                    tempReceive.OutboundTransforms = new List<string>();
                                    for (int i = 0; i < receivePort.OutboundTransforms.Count; i++)
                                        tempReceive.OutboundTransforms.Add(
                                            ((Transform)receivePort.OutboundTransforms[i]).FullName);
                                }
                            }

                            receiveList.Add(tempReceive);
                            break;
                        }
                    }
                    else
                    {
                        tempReceive = new BTReceivePort();
                        tempReceive.Name = receivePort.Name;
                        tempReceive.ApplicationName = receivePort.Application.Name;
                        tempReceive.Description = receivePort.Description;
                        tempReceive.CustomData = receivePort.CustomData;
                        tempReceive.Authentication = (int)receivePort.Authentication;
                        tempReceive.TwoWay = receivePort.IsTwoWay;
                        tempReceive.RouteFailed = receivePort.RouteFailedMessage;
                        tempReceive.ReceiveLocations = ReceiveLocations2(receivePort.ReceiveLocations, "");

                        if ((null != receivePort.InboundTransforms) && (receivePort.InboundTransforms.Count > 0))
                        {
                            tempReceive.InboundTransforms = new List<string>();
                            for (int i = 0; i < receivePort.InboundTransforms.Count; i++)
                                tempReceive.InboundTransforms.Add(
                                    ((Transform)receivePort.InboundTransforms[i]).FullName);
                        }

                        if (receivePort.IsTwoWay)
                        {
                            if ((null != receivePort.OutboundTransforms) && (receivePort.OutboundTransforms.Count > 0))
                            {
                                tempReceive.OutboundTransforms = new List<string>();
                                for (int i = 0; i < receivePort.OutboundTransforms.Count; i++)
                                    tempReceive.OutboundTransforms.Add(
                                        ((Transform)receivePort.OutboundTransforms[i]).FullName);
                            }
                        }

                        receiveList.Add(tempReceive);
                    }
                }
                return receiveList;
            }
            catch (System.Exception ex)
            {
                // log and throw new error
                EventLogger.Write(MethodInfo.GetCurrentMethod(), ex);
                throw;
            }
        }

        #endregion

        #region Receive Location Operations

        /// <summary>
        /// 
        /// </summary>
        /// <param name="receiveLocation"></param>
        public void CreateReceiveLocation(BTReceiveLocation receiveLocation)
        {
            if (String.IsNullOrEmpty(receiveLocation.ApplicationName))
                throw new ArgumentNullException("receiveLocation");
            if (String.IsNullOrEmpty(receiveLocation.ReceivePortName))
                throw new ArgumentNullException("receiveLocation");
            if (String.IsNullOrEmpty(receiveLocation.Name))
                throw new ArgumentNullException("receiveLocation");

            try
            {
                Application app = btsExplorer.Applications[receiveLocation.ApplicationName];
                if (null == app)
                    throw new BizTalkQueryUnexpectedException(Exceptions.BizTalkQueryApplicationNullMessage,
                                                              receiveLocation.ApplicationName);

                ReceivePort rPort = app.ReceivePorts[receiveLocation.ReceivePortName];
                if (null == rPort)
                    throw new BizTalkQueryUnexpectedException(Exceptions.BizTalkQueryRPNullMessage,
                                                              receiveLocation.ReceivePortName);

                ReceiveLocation rLoc = rPort.ReceiveLocations[receiveLocation.Name];
                if (null != rLoc)
                    throw new BizTalkQueryUnexpectedException(Exceptions.BizTalkQueryReceiveLocationExistsMessage,
                                                              receiveLocation.Name);

                rLoc = rPort.AddNewReceiveLocation();

                rLoc.Name = receiveLocation.Name;
                rLoc.Description = receiveLocation.Description;
                rLoc.CustomData = receiveLocation.CustomData;
                rLoc.Address = receiveLocation.Address;
                rLoc.TransportType = FindProtocolType(receiveLocation.TransportType);
                rLoc.TransportTypeData =
                    GenerateReceiveTransportTypeData(receiveLocation.TransportType, receiveLocation.TransportInfo);
                rLoc.ReceiveHandler = FindReceiveHandlerByTransportType(receiveLocation.TransportType);
                rLoc.ReceivePipeline =
                    PipelineByName(receiveLocation.ApplicationName, PipelineType.Receive,
                                   receiveLocation.ReceivePipelineName);
                if (receiveLocation.TwoWay)
                    rLoc.SendPipeline =
                        PipelineByName(receiveLocation.ApplicationName, PipelineType.Send,
                                       receiveLocation.SendPipelineName);
                rLoc.Enable = receiveLocation.Enabled;

                btsExplorer.SaveChanges();
            }
            catch (System.Exception ex)
            {
                btsExplorer.DiscardChanges();

                // log and throw new error
                EventLogger.LogMessage(EventFormatter.FormatEvent(MethodInfo.GetCurrentMethod(), ex),
                                       EventLogEntryType.Error, (int)EventLogger.EventId.BizTalkQuery);

                throw new BizTalkQueryUnexpectedException(Exceptions.BizTalkQueryCreateReceiveLocationMessage, ex);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="receiveLocation"></param>
        public void UpdateReceiveLocation(BTReceiveLocation receiveLocation)
        {
            if (String.IsNullOrEmpty(receiveLocation.ApplicationName))
                throw new ArgumentNullException("receiveLocation");
            if (String.IsNullOrEmpty(receiveLocation.ReceivePortName))
                throw new ArgumentNullException("receiveLocation");
            if (String.IsNullOrEmpty(receiveLocation.Name))
                throw new ArgumentNullException("receiveLocation");

            try
            {
                Application app = btsExplorer.Applications[receiveLocation.ApplicationName];
                if (null == app)
                    throw new BizTalkQueryUnexpectedException(Exceptions.BizTalkQueryApplicationNullMessage,
                                                              receiveLocation.ApplicationName);

                ReceivePort rPort = app.ReceivePorts[receiveLocation.ReceivePortName];
                if (null == rPort)
                    throw new BizTalkQueryUnexpectedException(Exceptions.BizTalkQueryRPNullMessage,
                                                              receiveLocation.ReceivePortName);

                ReceiveLocation rLoc = rPort.ReceiveLocations[receiveLocation.Name];
                if (null == rLoc)
                    throw new BizTalkQueryUnexpectedException(Exceptions.BizTalkQueryRLNullMessage, receiveLocation.Name);

                rLoc.Description = receiveLocation.Description;
                rLoc.CustomData = receiveLocation.CustomData;
                rLoc.Address = receiveLocation.Address;
                rLoc.TransportType = FindProtocolType(receiveLocation.TransportType);
                rLoc.TransportTypeData = GenerateReceiveTransportTypeData(receiveLocation.TransportType, receiveLocation.TransportInfo);
                rLoc.ReceiveHandler = FindReceiveHandlerByTransportType(receiveLocation.TransportType);
                rLoc.ReceivePipeline =
                    PipelineByName(receiveLocation.ApplicationName, PipelineType.Receive,
                                   receiveLocation.ReceivePipelineName);
                if (receiveLocation.TwoWay)
                    rLoc.SendPipeline =
                        PipelineByName(receiveLocation.ApplicationName, PipelineType.Send,
                                       receiveLocation.SendPipelineName);
                rLoc.Enable = receiveLocation.Enabled;

                btsExplorer.SaveChanges();
            }
            catch (System.Exception ex)
            {
                btsExplorer.DiscardChanges();

                // log and throw new error
                EventLogger.LogMessage(EventFormatter.FormatEvent(MethodInfo.GetCurrentMethod(), ex),
                                       EventLogEntryType.Error, (int)EventLogger.EventId.BizTalkQuery);

                throw new BizTalkQueryUnexpectedException(Exceptions.BizTalkQueryUpdateReceiveLocationMessage, ex,
                                                          receiveLocation.Name);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="receiveLocation"></param>
        public void DeleteReceiveLocation(BTReceiveLocation receiveLocation)
        {
            if (String.IsNullOrEmpty(receiveLocation.ApplicationName))
                throw new ArgumentNullException("receiveLocation");
            if (String.IsNullOrEmpty(receiveLocation.ReceivePortName))
                throw new ArgumentNullException("receiveLocation");
            if (String.IsNullOrEmpty(receiveLocation.Name))
                throw new ArgumentNullException("receiveLocation");

            try
            {
                Application app = btsExplorer.Applications[receiveLocation.ApplicationName];
                if (null == app)
                    throw new BizTalkQueryUnexpectedException(Exceptions.BizTalkQueryApplicationNullMessage,
                                                              receiveLocation.ApplicationName);

                ReceivePort rPort = app.ReceivePorts[receiveLocation.ReceivePortName];
                if (null == rPort)
                    throw new BizTalkQueryUnexpectedException(Exceptions.BizTalkQueryRPNullMessage,
                                                              receiveLocation.ReceivePortName);

                ReceiveLocation rLoc = rPort.ReceiveLocations[receiveLocation.Name];
                if (null == rLoc)
                    throw new BizTalkQueryUnexpectedException(Exceptions.BizTalkQueryRLNullMessage, receiveLocation.Name);

                rPort.RemoveReceiveLocation(rLoc);
                btsExplorer.SaveChanges();
            }
            catch (System.Exception ex)
            {
                btsExplorer.DiscardChanges();

                // log and throw new error
                EventLogger.LogMessage(EventFormatter.FormatEvent(MethodInfo.GetCurrentMethod(), ex),
                                       EventLogEntryType.Error, (int)EventLogger.EventId.BizTalkQuery);

                throw new BizTalkQueryUnexpectedException(Exceptions.BizTalkQueryDeleteReceiveLocationMessage, ex,
                                                          receiveLocation.Name);
            }
        }

        /// <summary>
        /// Gets all the Receive Locations Information. 
        /// Empty Location Name returns all Receive Locations.
        /// </summary>
        /// <param name="applicationName">Application Name</param>
        /// <param name="portName">Receive Port Name</param>
        /// <param name="name">Receive Location Name</param>
        /// <returns>BTQuery.BTSysStatus</returns>
        public List<BTReceiveLocation> ReceiveLocations(string applicationName, string portName, string name)
        {
            name = (String.IsNullOrEmpty(name)) ? String.Empty : name.Trim();
            try
            {
                Application app = (String.IsNullOrEmpty(applicationName))
                                      ? btsExplorer.DefaultApplication
                                      : btsExplorer.Applications[applicationName];
                if (null == app)
                    throw new BizTalkQueryUnexpectedException(Exceptions.BizTalkQueryApplicationNullMessage,
                                                              applicationName);

                ReceivePort rPort = app.ReceivePorts[portName];
                if (null == rPort)
                    return null;
                //throw new BizTalkQueryUnexpectedException(Exceptions.BizTalkQueryRPNullMessage, portName);

                return ReceiveLocations2(rPort.ReceiveLocations, name);
            }
            catch (BizTalkQueryUnexpectedException bizTalkEx)
            {
                // log and throw new error
                EventLogger.LogMessage(EventFormatter.FormatEvent(MethodInfo.GetCurrentMethod(), bizTalkEx),
                                       EventLogEntryType.Error, (int)EventLogger.EventId.BizTalkQuery);
                throw;
            }
            catch (System.Exception ex)
            {
                // log and throw new error
                EventLogger.LogMessage(EventFormatter.FormatEvent(MethodInfo.GetCurrentMethod(), ex),
                                       EventLogEntryType.Error, (int)EventLogger.EventId.BizTalkQuery);

                throw new BizTalkQueryUnexpectedException(Exceptions.BizTalkQueryGetReceiveLocationsMessage, ex, name);
            }
        }

        /// <summary>
        /// Internal Method to get all Receive Ports
        /// </summary>
        /// <param name="rcvLocColl">Receive Location List</param>
        /// <param name="name">receive location name to search for</param>
        /// <returns>Receivelocation List</returns>
        private static List<BTReceiveLocation> ReceiveLocations2(ReceiveLocationCollection rcvLocColl, string name)
        {
            List<BTReceiveLocation> rcvList = new List<BTReceiveLocation>();
            BTReceiveLocation tempRcvLoc;

            bool byName = !String.IsNullOrEmpty(name);

            try
            {
                foreach (ReceiveLocation rcvLoc in rcvLocColl)
                {
                    if (byName)
                    {
                        if (String.Compare(name, rcvLoc.Name, true, CultureInfo.CurrentCulture) == 0)
                        {
                            tempRcvLoc = new BTReceiveLocation();
                            tempRcvLoc.Name = rcvLoc.Name;
                            tempRcvLoc.ApplicationName = rcvLoc.ReceivePort.Application.Name;
                            tempRcvLoc.Description = rcvLoc.Description;
                            tempRcvLoc.CustomData = rcvLoc.CustomData;
                            tempRcvLoc.Address = rcvLoc.Address;
                            tempRcvLoc.TransportType = (null != rcvLoc.TransportType)
                                                           ? rcvLoc.TransportType.Name
                                                           : String.Empty;
                            tempRcvLoc.TransportTypeData = rcvLoc.TransportTypeData;
                            tempRcvLoc.ReceivePortName = rcvLoc.ReceivePort.Name;
                            tempRcvLoc.ReceiveHandlerName = rcvLoc.ReceiveHandler.Name;
                            tempRcvLoc.ReceivePipelineName = (null != rcvLoc.ReceivePipeline)
                                                                 ? rcvLoc.ReceivePipeline.FullName
                                                                 : String.Empty;
                            tempRcvLoc.SendPipelineName = (null != rcvLoc.SendPipeline)
                                                              ? rcvLoc.SendPipeline.FullName
                                                              : String.Empty;
                            tempRcvLoc.Enabled = rcvLoc.Enable;

                            rcvList.Add(tempRcvLoc);
                            break;
                        }
                    }
                    else
                    {
                        tempRcvLoc = new BTReceiveLocation();
                        tempRcvLoc.Name = rcvLoc.Name;
                        tempRcvLoc.Description = rcvLoc.Description;
                        tempRcvLoc.CustomData = rcvLoc.CustomData;
                        tempRcvLoc.Address = rcvLoc.Address;
                        tempRcvLoc.TransportType = (null != rcvLoc.TransportType)
                                                       ? rcvLoc.TransportType.Name
                                                       : String.Empty;
                        tempRcvLoc.TransportTypeData = rcvLoc.TransportTypeData;
                        tempRcvLoc.ReceivePortName = rcvLoc.ReceivePort.Name;
                        tempRcvLoc.ReceiveHandlerName = rcvLoc.ReceiveHandler.Name;
                        tempRcvLoc.ReceivePipelineName = (null != rcvLoc.ReceivePipeline)
                                                             ? rcvLoc.ReceivePipeline.FullName
                                                             : String.Empty;
                        tempRcvLoc.SendPipelineName = (null != rcvLoc.SendPipeline)
                                                          ? rcvLoc.SendPipeline.FullName
                                                          : String.Empty;
                        tempRcvLoc.Enabled = rcvLoc.Enable;

                        rcvList.Add(tempRcvLoc);
                    }
                }

                return rcvList;
            }
            catch (System.Exception ex)
            {
                // log and throw new error
                EventLogger.Write(MethodInfo.GetCurrentMethod(), ex);
                throw;
            }
        }

        #endregion

        #region Send Port Operations

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sendPort"></param>
        /// <param name="transportInfo"></param>
        public void CreateSendPort(BTSendPort sendPort)
        {
            if (String.IsNullOrEmpty(sendPort.ApplicationName))
                throw new ArgumentNullException("sendPort");
            if (String.IsNullOrEmpty(sendPort.Name))
                throw new ArgumentNullException("sendPort");

            try
            {
                Application app = btsExplorer.Applications[sendPort.ApplicationName];
                if (null == app)
                    throw new BizTalkQueryUnexpectedException(Exceptions.BizTalkQueryApplicationNullMessage,
                                                              sendPort.ApplicationName);

                SendPort sPort = app.SendPorts[sendPort.Name];
                if (null != sPort)
                    throw new BizTalkQueryUnexpectedException(Exceptions.BizTalkQuerySendPortExistsMessage,
                                                              sendPort.Name);

                sPort = app.AddNewSendPort(sendPort.IsDynamic, sendPort.TwoWay);

                sPort.Name = sendPort.Name;
                sPort.Description = sendPort.Description;
                //sPort.Filter = sendPort.Filter;
                sPort.RouteFailedMessage = sendPort.RouteFailed;
                sPort.OrderedDelivery = sendPort.OrderedDelivery;
                sPort.RouteFailedMessage = sendPort.RouteFailed;

                sPort.PrimaryTransport.TransportType = FindProtocolType(sendPort.TransportType);
                sPort.PrimaryTransport.TransportTypeData =
                    GenerateSendTransportTypeData(sendPort.TransportType, sendPort.TransportInfo);
                sPort.PrimaryTransport.Address = sendPort.Address;

                sPort.SendPipeline =
                    PipelineByName(sendPort.ApplicationName, PipelineType.Send, sendPort.SendPipelineName);
                if (sendPort.TwoWay)
                    sPort.ReceivePipeline =
                        PipelineByName(sendPort.ApplicationName, PipelineType.Receive, sendPort.ReceivePipelineName);

                if (null != sendPort.OutboundTransforms)
                {
                    foreach (string outboundTransform in sendPort.OutboundTransforms)
                    {
                        for (int i = 0; i < app.Transforms.Count; i++)
                        {
                            if (app.Transforms[i].FullName == outboundTransform)
                            {
                                sPort.OutboundTransforms.Add(app.Transforms[i]);
                                break;
                            }
                        }
                    }
                }

                if (sendPort.TwoWay)
                {
                    if (null != sendPort.InboundTransforms)
                    {
                        foreach (string inboundTransform in sendPort.InboundTransforms)
                        {
                            for (int i = 0; i < app.Transforms.Count; i++)
                            {
                                if (app.Transforms[i].FullName == inboundTransform)
                                {
                                    sPort.InboundTransforms.Add(app.Transforms[i]);
                                    break;
                                }
                            }
                        }
                    }
                }

                btsExplorer.SaveChanges();
            }
            catch (System.Exception ex)
            {
                btsExplorer.DiscardChanges();

                // log and throw new error
                EventLogger.LogMessage(EventFormatter.FormatEvent(MethodInfo.GetCurrentMethod(), ex),
                                       EventLogEntryType.Error, (int)EventLogger.EventId.BizTalkQuery);

                throw new BizTalkQueryUnexpectedException(Exceptions.BizTalkQueryCreateSendPortMessage, ex);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sendPort"></param>
        public void UpdateSendPort(BTSendPort sendPort)
        {
            if (String.IsNullOrEmpty(sendPort.ApplicationName))
                throw new ArgumentNullException("sendPort");
            if (String.IsNullOrEmpty(sendPort.Name))
                throw new ArgumentNullException("sendPort");

            try
            {
                Application app = btsExplorer.Applications[sendPort.ApplicationName];
                if (null == app)
                    throw new BizTalkQueryUnexpectedException(Exceptions.BizTalkQueryApplicationNullMessage,
                                                              sendPort.ApplicationName);

                SendPort sPort = app.SendPorts[sendPort.Name];
                if (null == sPort)
                    throw new BizTalkQueryUnexpectedException(Exceptions.BizTalkQuerySPNullMessage, sendPort.Name);

                sPort.Description = sendPort.Description;
                //sPort.Filter = sendPort.Filter ?? String.Empty;
                sPort.RouteFailedMessage = sendPort.RouteFailed;
                sPort.OrderedDelivery = sendPort.OrderedDelivery;
                sPort.RouteFailedMessage = sendPort.RouteFailed;

                sPort.PrimaryTransport.TransportType = FindProtocolType(sendPort.TransportType);
                sPort.PrimaryTransport.TransportTypeData =
                    GenerateSendTransportTypeData(sendPort.TransportType, sendPort.TransportInfo);
                sPort.PrimaryTransport.Address = sendPort.Address;

                sPort.SendPipeline =
                    PipelineByName(sendPort.ApplicationName, PipelineType.Send, sendPort.SendPipelineName);
                if (sendPort.TwoWay)
                    sPort.ReceivePipeline =
                        PipelineByName(sendPort.ApplicationName, PipelineType.Receive, sendPort.ReceivePipelineName);

                if (null != sendPort.OutboundTransforms)
                {
                    foreach (string outboundTransform in sendPort.OutboundTransforms)
                    {
                        for (int i = 0; i < app.Transforms.Count; i++)
                        {
                            if (app.Transforms[i].FullName == outboundTransform)
                            {
                                sPort.OutboundTransforms.Add(app.Transforms[i]);
                                break;
                            }
                        }
                    }
                }

                if (sendPort.TwoWay)
                {
                    if (null != sendPort.InboundTransforms)
                    {
                        foreach (string inboundTransform in sendPort.InboundTransforms)
                        {
                            for (int i = 0; i < app.Transforms.Count; i++)
                            {
                                if (app.Transforms[i].FullName == inboundTransform)
                                {
                                    sPort.InboundTransforms.Add(app.Transforms[i]);
                                    break;
                                }
                            }
                        }
                    }
                }

                btsExplorer.SaveChanges();
            }
            catch (System.Exception ex)
            {
                btsExplorer.DiscardChanges();

                // log and throw new error
                EventLogger.LogMessage(EventFormatter.FormatEvent(MethodInfo.GetCurrentMethod(), ex),
                                       EventLogEntryType.Error, (int)EventLogger.EventId.BizTalkQuery);

                throw new BizTalkQueryUnexpectedException(Exceptions.BizTalkQueryUpdateSendPortMessage, ex,
                                                          sendPort.Name);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sendPort"></param>
        public void DeleteSendPort(BTSendPort sendPort)
        {
            if (String.IsNullOrEmpty(sendPort.Name))
                throw new ArgumentNullException("sendPort");

            try
            {
                SendPort sPort = btsExplorer.SendPorts[sendPort.Name];
                if (null == sPort)
                    throw new BizTalkQueryUnexpectedException(Exceptions.BizTalkQueryRPNullMessage, sendPort.Name);

                btsExplorer.RemoveSendPort(sPort);
                btsExplorer.SaveChanges();
            }
            catch (System.Exception ex)
            {
                btsExplorer.DiscardChanges();

                // log and throw new error
                EventLogger.LogMessage(EventFormatter.FormatEvent(MethodInfo.GetCurrentMethod(), ex),
                                       EventLogEntryType.Error, (int)EventLogger.EventId.BizTalkQuery);

                throw new BizTalkQueryUnexpectedException(Exceptions.BizTalkQueryDeleteSendPortMessage, ex,
                                                          sendPort.Name);
            }
        }

        /// <summary>
        /// Gets all the Send Port Information. 
        /// Empty Port Name returns all Send Ports.
        /// </summary>
        /// <param name="applicationName">Application Name</param>
        /// <param name="name">Send Port Name</param>
        /// <returns>List<BTSendPort></returns>
        public List<BTSendPort> SendPorts(string applicationName, string name)
        {
            name = (String.IsNullOrEmpty(name)) ? String.Empty : name.Trim();
            try
            {
                Application app = (String.IsNullOrEmpty(applicationName))
                                      ? btsExplorer.DefaultApplication
                                      : btsExplorer.Applications[applicationName];
                if (null == app)
                    throw new BizTalkQueryUnexpectedException(Exceptions.BizTalkQueryApplicationNullMessage,
                                                              applicationName);

                return SendPorts2(app.SendPorts, name);
            }
            catch (BizTalkQueryUnexpectedException bizTalkEx)
            {
                // log and throw new error
                EventLogger.LogMessage(EventFormatter.FormatEvent(MethodInfo.GetCurrentMethod(), bizTalkEx),
                                       EventLogEntryType.Error, (int)EventLogger.EventId.BizTalkQuery);
                throw;
            }
            catch (System.Exception ex)
            {
                // log and throw new error
                EventLogger.LogMessage(EventFormatter.FormatEvent(MethodInfo.GetCurrentMethod(), ex),
                                       EventLogEntryType.Error, (int)EventLogger.EventId.BizTalkQuery);

                throw new BizTalkQueryUnexpectedException(Exceptions.BizTalkQueryGetSendPortsMessage, ex, name);
            }
        }

        /// <summary>
        /// Gets the Send Port Information by querying the BizTalk Management Database
        /// Empty send port Name returns all send ports else returns specific send port information.
        /// </summary>
        /// <param name="sendPortColl">Send Port List</param>
        /// <param name="name">Send port name to search for</param>
        /// <returns>BTSendPort List</returns>
        private static List<BTSendPort> SendPorts2(SendPortCollection sendPortColl, string name)
        {
            List<BTSendPort> sendList = new List<BTSendPort>();
            BTSendPort tempSend;
            bool byName = !String.IsNullOrEmpty(name);

            try
            {
                foreach (SendPort sendPort in sendPortColl)
                {
                    if (byName)
                    {
                        if (String.Compare(name, sendPort.Name, true, CultureInfo.CurrentCulture) == 0)
                        {
                            tempSend = new BTSendPort();
                            tempSend.Name = sendPort.Name;
                            tempSend.SendPipelineName = (null != sendPort.SendPipeline)
                                                            ? sendPort.SendPipeline.FullName
                                                            : String.Empty;
                            tempSend.ReceivePipelineName = (null != sendPort.ReceivePipeline)
                                                               ? sendPort.ReceivePipeline.FullName
                                                               : String.Empty;
                            tempSend.Description = sendPort.Description;
                            tempSend.IsDynamic = sendPort.IsDynamic;
                            tempSend.TwoWay = sendPort.IsTwoWay;
                            tempSend.Filter = sendPort.Filter;
                            tempSend.ApplicationName = sendPort.Application.Name;
                            tempSend.Status = sendPort.Status.ToString();
                            tempSend.RouteFailed = sendPort.RouteFailedMessage;
                            if (sendPort.PrimaryTransport != null)
                            {
                                tempSend.TransportType = FixTransportType(sendPort.PrimaryTransport.TransportType.Name);
                                tempSend.TransportTypeData = sendPort.PrimaryTransport.TransportTypeData;
                                tempSend.Address = sendPort.PrimaryTransport.Address;
                                tempSend.SendHandlerName = sendPort.PrimaryTransport.SendHandler.Name;
                            }

                            sendList.Add(tempSend);
                            break;
                        }
                    }
                    else
                    {
                        tempSend = new BTSendPort();
                        tempSend.Name = sendPort.Name;
                        tempSend.SendPipelineName = (null != sendPort.SendPipeline)
                                                        ? sendPort.SendPipeline.FullName
                                                        : String.Empty;
                        tempSend.ReceivePipelineName = (null != sendPort.ReceivePipeline)
                                                           ? sendPort.ReceivePipeline.FullName
                                                           : String.Empty;
                        tempSend.Description = sendPort.Description;
                        tempSend.IsDynamic = sendPort.IsDynamic;
                        tempSend.TwoWay = sendPort.IsTwoWay;
                        tempSend.Filter = sendPort.Filter;
                        tempSend.ApplicationName = sendPort.Application.Name;
                        tempSend.Status = sendPort.Status.ToString();
                        tempSend.RouteFailed = sendPort.RouteFailedMessage;
                        if (sendPort.PrimaryTransport != null)
                        {
                            tempSend.TransportType = FixTransportType(sendPort.PrimaryTransport.TransportType.Name);
                            tempSend.TransportTypeData = sendPort.PrimaryTransport.TransportTypeData;
                            tempSend.Address = sendPort.PrimaryTransport.Address;
                            tempSend.SendHandlerName = sendPort.PrimaryTransport.SendHandler.Name;
                        }

                        sendList.Add(tempSend);
                    }
                }
                return sendList;
            }
            catch (System.Exception ex)
            {
                // log and throw new error
                EventLogger.Write(MethodInfo.GetCurrentMethod(), ex);
                throw;
            }
        }

        #endregion

        #region Schema Operations

        /// <summary>
        /// 
        /// </summary>
        /// <param name="applicationName"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public List<BTSchema> Schemas(string applicationName, string name)
        {
            bool byName = false;

            if (false == String.IsNullOrEmpty(name))
            {
                byName = true;
                name = name.Trim();
            }
            else
                name = String.Empty;

            BTSchema tempSchema;
            List<BTSchema> schemaList = new List<BTSchema>();

            try
            {
                Application app = (String.IsNullOrEmpty(applicationName))
                                      ? btsExplorer.DefaultApplication
                                      : btsExplorer.Applications[applicationName];
                if (null == app)
                    throw new BizTalkQueryUnexpectedException(Exceptions.BizTalkQueryApplicationNullMessage,
                                                              applicationName);

                if (byName)
                {
                    Schema schema = app.Schemas[name];
                    if (null == schema)
                        throw new BizTalkQueryUnexpectedException(Exceptions.BizTalkQuerySchemaNullMessage, name);

                    tempSchema = new BTSchema();
                    tempSchema.ApplicationName = applicationName;
                    tempSchema.AssemblyQualifiedName = schema.AssemblyQualifiedName;
                    tempSchema.Description = schema.Description;
                    tempSchema.FullName = schema.FullName;
                    tempSchema.RootName = schema.RootName;
                    tempSchema.TargetNameSpace = schema.TargetNameSpace;
                    tempSchema.Type = schema.Type;
                    tempSchema.XmlContent = schema.XmlContent;

                    schemaList.Add(tempSchema);
                }
                else
                {
                    foreach (Schema schema in app.Schemas)
                    {
                        tempSchema = new BTSchema();
                        tempSchema.ApplicationName = applicationName;
                        tempSchema.AssemblyQualifiedName = schema.AssemblyQualifiedName;
                        tempSchema.Description = schema.Description;
                        tempSchema.FullName = schema.FullName;
                        tempSchema.RootName = schema.RootName;
                        tempSchema.TargetNameSpace = schema.TargetNameSpace;
                        tempSchema.Type = schema.Type;
                        tempSchema.XmlContent = schema.XmlContent;

                        schemaList.Add(tempSchema);
                    }
                }

                return schemaList;
            }
            catch (BizTalkQueryUnexpectedException bizTalkEx)
            {
                // log and throw new error
                EventLogger.LogMessage(EventFormatter.FormatEvent(MethodInfo.GetCurrentMethod(), bizTalkEx),
                                       EventLogEntryType.Error, (int)EventLogger.EventId.BizTalkQuery);
                throw;
            }
            catch (System.Exception ex)
            {
                // log and throw new error
                EventLogger.LogMessage(EventFormatter.FormatEvent(MethodInfo.GetCurrentMethod(), ex),
                                       EventLogEntryType.Error, (int)EventLogger.EventId.BizTalkQuery);

                throw new BizTalkQueryUnexpectedException(Exceptions.BizTalkQueryGetSchemasMessage, ex, applicationName,
                                                          name);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="applicationName"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public List<BTSchema> SchemasByType(string applicationName, string type)
        {
            BTSchema tempSchema;
            List<BTSchema> schemaList = new List<BTSchema>();

            try
            {
                Application app = (String.IsNullOrEmpty(applicationName))
                                      ? btsExplorer.DefaultApplication
                                      : btsExplorer.Applications[applicationName];
                if (null == app)
                    throw new BizTalkQueryUnexpectedException(Exceptions.BizTalkQueryApplicationNullMessage,
                                                              applicationName);

                foreach (Schema schema in app.Schemas)
                {
                    if (schema.Type.ToString() == type)
                    {
                        tempSchema = new BTSchema();
                        tempSchema.ApplicationName = applicationName;
                        tempSchema.AssemblyQualifiedName = schema.AssemblyQualifiedName;
                        tempSchema.Description = schema.Description;
                        tempSchema.FullName = schema.FullName;
                        tempSchema.RootName = schema.RootName;
                        tempSchema.TargetNameSpace = schema.TargetNameSpace;
                        tempSchema.Type = schema.Type;
                        tempSchema.XmlContent = schema.XmlContent;

                        schemaList.Add(tempSchema);
                    }
                }
            }
            catch (BizTalkQueryUnexpectedException bizTalkEx)
            {
                // log and throw new error
                EventLogger.LogMessage(EventFormatter.FormatEvent(MethodInfo.GetCurrentMethod(), bizTalkEx),
                                       EventLogEntryType.Error, (int)EventLogger.EventId.BizTalkQuery);
                throw;
            }
            catch (System.Exception ex)
            {
                // log and throw new error
                EventLogger.LogMessage(EventFormatter.FormatEvent(MethodInfo.GetCurrentMethod(), ex),
                                       EventLogEntryType.Error, (int)EventLogger.EventId.BizTalkQuery);

                throw new BizTalkQueryUnexpectedException(Exceptions.BizTalkQueryGetSchemasMessage, ex, applicationName,
                                                          "");
            }

            return schemaList;
        }

        //public bool IsValidXML(string xmlContent)
        //{
        //    FFDasmComp ffdcomp = new FFDasmComp();
        //    IPipelineContext pc = new IPipelineContext();
        //    IBaseMessageFactory msgFactory = pc.GetMessageFactory();
        //    IBaseMessage msg = msgFactory.CreateMessage();
        //    msg.BodyPart.Data = new MemoryStream();

        //    ffdcomp.InitNew();
        //    ffdcomp.Disassemble(pc, msg);
        //    IBaseMessage msg2 = ffdcomp.GetNext(null); 
        //    return true;
        //}

        #endregion

        #region Pipeline Operations

        /// <summary>
        /// 
        /// </summary>
        /// <param name="applicationName"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public List<BTPipeline> Pipelines(string applicationName, string name)
        {
            bool byName = false;

            if (false == String.IsNullOrEmpty(name))
            {
                byName = true;
                name = name.Trim();
            }
            else
                name = String.Empty;

            BTPipeline tempPipeline;
            List<BTPipeline> pipelineList = new List<BTPipeline>();

            try
            {
                Application app = (String.IsNullOrEmpty(applicationName))
                                      ? btsExplorer.DefaultApplication
                                      : btsExplorer.Applications[applicationName];
                if (null == app)
                    throw new BizTalkQueryUnexpectedException(Exceptions.BizTalkQueryApplicationNullMessage,
                                                              applicationName);

                if (byName)
                {
                    Pipeline pipeline = app.Pipelines[name];
                    if (null == pipeline)
                        throw new BizTalkQueryUnexpectedException(Exceptions.BizTalkQueryPipelineNullMessage, name);

                    tempPipeline = new BTPipeline();
                    tempPipeline.ApplicationName = applicationName;
                    tempPipeline.AssemblyQualifiedName = pipeline.AssemblyQualifiedName;
                    tempPipeline.Description = pipeline.Description;
                    tempPipeline.FullName = pipeline.FullName;
                    tempPipeline.Type = pipeline.Type;

                    pipelineList.Add(tempPipeline);
                }
                else
                {
                    foreach (Pipeline schema in app.Pipelines)
                    {
                        tempPipeline = new BTPipeline();
                        tempPipeline.ApplicationName = applicationName;
                        tempPipeline.AssemblyQualifiedName = schema.AssemblyQualifiedName;
                        tempPipeline.Description = schema.Description;
                        tempPipeline.FullName = schema.FullName;
                        tempPipeline.Type = schema.Type;

                        pipelineList.Add(tempPipeline);
                    }
                }

                return pipelineList;
            }
            catch (BizTalkQueryUnexpectedException bizTalkEx)
            {
                // log and throw new error
                EventLogger.LogMessage(EventFormatter.FormatEvent(MethodInfo.GetCurrentMethod(), bizTalkEx),
                                       EventLogEntryType.Error, (int)EventLogger.EventId.BizTalkQuery);
                throw;
            }
            catch (System.Exception ex)
            {
                // log and throw new error
                EventLogger.LogMessage(EventFormatter.FormatEvent(MethodInfo.GetCurrentMethod(), ex),
                                       EventLogEntryType.Error, (int)EventLogger.EventId.BizTalkQuery);

                throw new BizTalkQueryUnexpectedException(Exceptions.BizTalkQueryGetPipelinesMessage, ex,
                                                          applicationName, name);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="applicationName"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public List<BTPipeline> PipelinesByType(string applicationName, string type)
        {
            BTPipeline tempPipeline;
            List<BTPipeline> pipelineList = new List<BTPipeline>();

            try
            {
                Application app = (String.IsNullOrEmpty(applicationName))
                                      ? btsExplorer.DefaultApplication
                                      : btsExplorer.Applications[applicationName];
                if (null == app)
                    throw new BizTalkQueryUnexpectedException(Exceptions.BizTalkQueryApplicationNullMessage,
                                                              applicationName);

                foreach (Pipeline pipeline in app.Pipelines)
                {
                    if (pipeline.Type.ToString() == type)
                    {
                        tempPipeline = new BTPipeline();
                        tempPipeline.ApplicationName = applicationName;
                        tempPipeline.AssemblyQualifiedName = pipeline.AssemblyQualifiedName;
                        tempPipeline.Description = pipeline.Description;
                        tempPipeline.FullName = pipeline.FullName;
                        tempPipeline.Type = pipeline.Type;

                        pipelineList.Add(tempPipeline);
                    }
                }

                return pipelineList;
            }
            catch (BizTalkQueryUnexpectedException bizTalkEx)
            {
                // log and throw new error
                EventLogger.LogMessage(EventFormatter.FormatEvent(MethodInfo.GetCurrentMethod(), bizTalkEx),
                                       EventLogEntryType.Error, (int)EventLogger.EventId.BizTalkQuery);
                throw;
            }
            catch (System.Exception ex)
            {
                // log and throw new error
                EventLogger.LogMessage(EventFormatter.FormatEvent(MethodInfo.GetCurrentMethod(), ex),
                                       EventLogEntryType.Error, (int)EventLogger.EventId.BizTalkQuery);

                throw new BizTalkQueryUnexpectedException(Exceptions.BizTalkQueryGetPipelinesMessage, ex,
                                                          applicationName, "");
            }
        }

        private Pipeline PipelineByName(string applicationName, PipelineType type, string name)
        {
            if (String.IsNullOrEmpty(name))
                throw new ArgumentNullException("name");

            try
            {
                Application app = (String.IsNullOrEmpty(applicationName))
                                      ? btsExplorer.DefaultApplication
                                      : btsExplorer.Applications[applicationName];
                if (null == app)
                    throw new BizTalkQueryUnexpectedException(Exceptions.BizTalkQueryApplicationNullMessage,
                                                              applicationName);

                foreach (Pipeline pipeline in app.Pipelines)
                {
                    if ((pipeline.Type == type) && (name == pipeline.FullName))
                        return pipeline;
                }

                foreach (Pipeline pipeline in btsExplorer.Pipelines)
                {
                    if ((pipeline.Type == type) && (name == pipeline.FullName))
                        return pipeline;
                }

                return null;
            }
            catch (BizTalkQueryUnexpectedException bizTalkEx)
            {
                // log and throw new error
                EventLogger.LogMessage(EventFormatter.FormatEvent(MethodInfo.GetCurrentMethod(), bizTalkEx),
                                       EventLogEntryType.Error, (int)EventLogger.EventId.BizTalkQuery);
                throw;
            }
            catch (System.Exception ex)
            {
                // log and throw new error
                EventLogger.LogMessage(EventFormatter.FormatEvent(MethodInfo.GetCurrentMethod(), ex),
                                       EventLogEntryType.Error, (int)EventLogger.EventId.BizTalkQuery);

                throw new BizTalkQueryUnexpectedException(Exceptions.BizTalkQueryGetPipelinesMessage, ex,
                                                          applicationName, "");
            }
        }

        #endregion

        #region Transform Operations

        public List<BTTransform> Transforms(string applicationName, string name)
        {
            bool byName = false;

            if (false == String.IsNullOrEmpty(name))
            {
                byName = true;
                name = name.Trim();
            }
            else
                name = String.Empty;

            BTTransform tempTransform;
            List<BTTransform> transformList = new List<BTTransform>();

            try
            {
                Application app = (String.IsNullOrEmpty(applicationName))
                                      ? btsExplorer.DefaultApplication
                                      : btsExplorer.Applications[applicationName];
                if (null == app)
                    throw new BizTalkQueryUnexpectedException(Exceptions.BizTalkQueryApplicationNullMessage,
                                                              applicationName);

                if (byName)
                {
                    Transform transform = app.Transforms[name];
                    if (null == transform)
                        throw new BizTalkQueryUnexpectedException(Exceptions.BizTalkQueryTransformNullMessage, name);

                    tempTransform = new BTTransform();
                    tempTransform.ApplicationName = applicationName;
                    tempTransform.AssemblyQualifiedName = transform.AssemblyQualifiedName;
                    tempTransform.Description = transform.Description;
                    tempTransform.FullName = transform.FullName;
                    tempTransform.SourceSchema = transform.SourceSchema.FullName;
                    tempTransform.TargetSchema = transform.TargetSchema.FullName;

                    transformList.Add(tempTransform);
                }
                else
                {
                    foreach (Transform transform in app.Transforms)
                    {
                        tempTransform = new BTTransform();
                        tempTransform.ApplicationName = applicationName;
                        tempTransform.AssemblyQualifiedName = transform.AssemblyQualifiedName;
                        tempTransform.Description = transform.Description;
                        tempTransform.FullName = transform.FullName;
                        tempTransform.SourceSchema = transform.SourceSchema.FullName;
                        tempTransform.TargetSchema = transform.TargetSchema.FullName;

                        transformList.Add(tempTransform);
                    }
                }

                return transformList;
            }
            catch (BizTalkQueryUnexpectedException bizTalkEx)
            {
                // log and throw new error
                EventLogger.LogMessage(EventFormatter.FormatEvent(MethodInfo.GetCurrentMethod(), bizTalkEx),
                                       EventLogEntryType.Error, (int)EventLogger.EventId.BizTalkQuery);
                throw;
            }
            catch (System.Exception ex)
            {
                // log and throw new error
                EventLogger.LogMessage(EventFormatter.FormatEvent(MethodInfo.GetCurrentMethod(), ex),
                                       EventLogEntryType.Error, (int)EventLogger.EventId.BizTalkQuery);

                throw new BizTalkQueryUnexpectedException(Exceptions.BizTalkQueryGetTransformsMessage, ex,
                                                          applicationName, name);
            }
        }

        #endregion
    }
}